I'm trying to keep the camera above a plane which acts as the ground, so I wrote this bit of code:

RaycastHit hit;
if (!Physics.Raycast (transform.position, new Vector3 (0, -50, 0), out hit, 5)) {
    transform.position = new Vector3 (0, 20, 0);
    Debug.Log ("No ground found when raycasting down!");
    Debug.DrawRay (transform.position, new Vector3 (0, -50, 0), Color.red, 0, true);
} else {
    if (hit.distance <= 1) {
        transform.position = new Vector3 (transform.position.x, 1, transform.position.z);

The camera is clearly over the plane on position 0, 20, 0 while the plane is at 1, 1, 1, with scale 50, 1, 50, but it never detects a hit. The ray drawn by DrawRay() does intersect the plane.

The plane is oriented upwards, but just to be sure I tried raycasting from below as well, without success.

I have also tried replacing the mesh collider with a box collider using size 10, 1, 10 (I'm not sure why, this seems to be the same size as my scaled plane) and 10, 10, 10. Neither worked.

What Am I missing?

  • \$\begingroup\$ Are your colliders set as triggers? \$\endgroup\$ – hobnob Jul 25 '16 at 9:47
  • \$\begingroup\$ @hobnob I have tried both with and without setting them as triggers \$\endgroup\$ – Annonymus Jul 25 '16 at 9:47
  • \$\begingroup\$ Is the ray hitting any other objects? Have you tried RaycastAll instead? \$\endgroup\$ – jgallant Jul 25 '16 at 9:57

I found the problem while modifying my code to try out Jon's sugestions. Somehow I added a max distance of 5 to the RayCast. Must have gotten confused with the many overloads or something.

It works if I modify the second line like this:

if (!Physics.Raycast (transform.position, new Vector3 (0, -50, 0), out hit/*, 5*/)) {
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.