Raycast problem

Hello!

I’ve got a problem while trying to get familiar with raycasting. I send a ray, and checks if its hit something, but when I try to get the hitpoint, it gives wrong point.

Code:

RaycastHit hit;
var mousePo = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y,Camera.main.nearClipPlane));
Ray r = Camera.main.ScreenPointToRay(mousePo);
Physics.Raycast(r, out hit);
Debug.DrawRay(r.origin, hit.point, Color.green);

Hey Robee,

I think your logic is ok but there is a simpler way.

    var hit = new RaycastHit();
    var ray = yourCamera.ScreenPointToRay(Input.mousePosition);

    if(Physics.Raycast(ray, out hit)) 
    {
       Debug.DrawRay(ray.origin, hit.point, Color.green);
    }

Also, using Camera.main is tricky because if you have multiple cameras tagged MainCamera you will never be sure which one is returned by the property (it grabs the first one it finds). It’s always better to assign your cameras explicitly either through a public field or at script initialization.

This will save you headaches and hours of debugging.

Hope this helps,
Alex