Efficient Ray Collision Detection Against a Single Object
光线在Unity中对于实现碰撞和UI交互非常有用. A typical way to use them is provided by the official documentation:
RaycastHit hit;
float distanceToGround = 0;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0F)) {
// Determine which object is using hit.collider and do something with it
}
The equivalent for detecting all objects hit is:
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
However, 如果我们只是想看看一个特定的物体是否挡住了光线呢, without going through a list of them, and we are not sure (or don’t care) if it’s a hit? 我们可以通过从它的边界开始而不是从射线开始来检查单个物体, using the Bounds.IntersectsRay
method:
Ray ray = ... // our ray
GameObject go = ... // our game object
Collider collider = go.GetComponent();
if (collider.bounds.IntersectsRay(ray)) {
// object hit!
}
This can also be used with the Bounds
object provided by a MeshRenderer
.