以下是一些常见的碰撞检测方法:
Physics.Raycast:
用于从一个点发射射线,检测是否与物体碰撞。
可以用于检测直线上的碰撞物体。
RaycastHit hitInfo;
if (Physics.Raycast(origin, direction, out hitInfo, maxDistance, layerMask))
{
// 处理碰撞
Debug.Log("碰撞到物体: " + hitInfo.collider.gameObject.name);
}
Physics.SphereCast:
类似于Raycast,但是以球体形状来检测碰撞。
可用于检测球体在路径上的碰撞。
RaycastHit hitInfo;
if (Physics.SphereCast(origin, radius, direction, out hitInfo, maxDistance, layerMask))
{
// 处理碰撞
Debug.Log("碰撞到物体: " + hitInfo.collider.gameObject.name);
}
Physics.BoxCast:
类似于Raycast,但使用盒子形状来检测碰撞。
可用于检测盒子在路径上的碰撞。
RaycastHit hitInfo;
if (Physics.BoxCast(center, halfExtents, direction, out hitInfo, orientation, maxDistance, layerMask))
{
// 处理碰撞
Debug.Log("碰撞到物体: " + hitInfo.collider.gameObject.name);
}
Physics.CapsuleCast:
类似于Raycast,但使用胶囊体形状来检测碰撞。
可用于检测胶囊体在路径上的碰撞。
RaycastHit hitInfo;
if (Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, maxDistance, layerMask))
{
// 处理碰撞
Debug.Log("碰撞到物体: " + hitInfo.collider.gameObject.name);
}
Physics.OverlapSphere:
用于检测球形区域内的物体碰撞。
返回与球形区域重叠的碰撞器数组。
Collider[] colliders = Physics.OverlapSphere(position, radius, layerMask);
foreach (Collider collider in colliders)
{
// 处理碰撞
Debug.Log("碰撞到物体: " + collider.gameObject.name);
}
Physics.OverlapBox:
用于检测盒子形状区域内的物体碰撞。
返回与盒子区域重叠的碰撞器数组。
Collider[] colliders = Physics.OverlapBox(center, halfExtents, orientation, layerMask);
foreach (Collider collider in colliders)
{
// 处理碰撞
Debug.Log("碰撞到物体: " + collider.gameObject.name);
}
Physics.OverlapCapsule:
用于检测胶囊体形状区域内的物体碰撞。
返回与胶囊体区域重叠的碰撞器数组。
Collider[] colliders = Physics.OverlapCapsule(point0, point1, radius, layerMask);
foreach (Collider collider in colliders)
{
// 处理碰撞
Debug.Log("碰撞到物体: " + collider.gameObject.name);
}