Search code examples
c#unity-game-engineraytracing

Draw debug ray in perspective mode


I've had success casting and drawing debug rays with an Orthographic camera, but I change this to Perspective and none of my rays seem to work anymore (in the scene view, my debug ray is not moving with my mouse).

This was my code for Orthographic, what do I need to do differently for perspective?

public class Cursor : MonoBehaviour {

// 45 degree angle down, same as camera angle
private Vector3 gameAngle = new Vector3(0, -45, -45);
public RaycastHit hit;
public Ray ray;

void Update() {
    // Rays
    ray = new Ray(Camera.main.ScreenToWorldPoint(Input.mousePosition), gameAngle);
    if (Debug.isDebugBuild)
        Debug.DrawRay(Camera.main.ScreenToWorldPoint(Input.mousePosition), gameAngle * 20, Color.green);    
}

}

Solution

  • I guess straight from the docs is the answer http://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

    Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);