- Home /
Why would a collider.Raycast not register a hit when collider.bounds.IntersectRay does?
I'm having trouble getting a raycast to work. I attach the following script to a cube object. The ray it creates intersects the bounds of the cube. The bounds of the collider detects the ray's intersection, but the collider itself doesn't register a hit when raycasted. What might cause the raycast to return false?
using UnityEngine;
using System.Collections;
public class RaycastTest : MonoBehaviour {
// Update is called once per frame
void Update () {
// Make a ray that definitely intersects our box collider
Ray ray = new Ray(gameObject.collider.bounds.center, Vector3.one);
Debug.DrawLine (ray.origin, ray.origin + ray.direction, Color.red);
// Cast the ray three different ways, expecting all to return true;
RaycastHit hitInfo;
bool hitBounds = gameObject.collider.bounds.IntersectRay(ray);
bool hitCollider = gameObject.collider.Raycast(ray, out hitInfo, ray.direction.magnitude);
bool hitAnyCollider = Physics.Raycast(ray, out hitInfo);
// Expecting all hits to be true always
Debug.Log (ray.ToString () + hitBounds.ToString () + hitCollider.ToString () + hitAnyCollider.ToString ());
// hitBounds is always true.
// hitCollider and hitAnyCollider are always false. Why?
}
}
The box collider's IsTrigger=false. The cube is not on the IgnoreRaycast layer.
Answer by robertbu · Sep 28, 2013 at 09:42 PM
Colliders, like meshes, are one sided. Casting from inside a cube outward will not generate a hit. You have to cast from outside the cube towards the cube to get a hit. If you describe what you are trying to accomplish, maybe I can suggest an alternate method.
Thanks very much. Reversing the ray made the difference in the example. This tells me that raycasting isn't so practical for containment testing and that colliders are a better method. I was trying to avoid having to create a lot of colliders by using raycasting. I have a sweeping zone (a cube) which I want a lot of mesh objects to react to.