-1

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);    
}

}
Olivier Moindrot
  • 27,908
  • 11
  • 92
  • 91
user3822370
  • 641
  • 7
  • 20

3 Answers3

1

Fisrt we need to know what the DrawRay function expects from parameters

It wants the origin point, the direction and the distance of the ray (you can also give it a color, and other parameters).

public static void DrawRay(Vector3 start, Vector3 dir, Color color = Color.white, float duration = 0.0f, bool depthTest = true);

So now we need to know the direction between our ray origin and our ray.point position, to find we can use a substraction...

If one point in space is subtracted from another, then the result is a vector that “points” from one object to the other:

// Gets a vector that points from the player's position to the target's.
var heading = hit.point - ray.origin;

Now with this info we can get the direction and the distance of our ray

var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.

And this will be the resulting code...

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

if (Physics.Raycast(ray, out hit))
{
   // Gets a vector that points from the player's position to the target's.
   var heading = hit.point - ray.origin;
   var distance = heading.magnitude;
   var direction = heading / distance; // This is now the normalized direction.

   Debug.DrawRay(ray.origin, direction * distance, Color.red);

 }

https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html

0

Have you tried changing the perspective? I'm assuming you have 2d mode on.

0

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);
user3822370
  • 641
  • 7
  • 20