Efficient Ray Collision Detection Against a Single Object
Rays are very useful in Unity for implementing collisions and UI interaction, among other things. 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, what if we just want to see if a specific object is in the way of the ray, without going through a list of them, and we are not sure (or don’t care) if it’s a hit? We can check specifically for a single object by starting from its bounds instead of from the Ray, 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
.