# Raycast wrong direction

I use Physics.Raycast and transform.forward to shoot a ray in front of my gameobject, but the ray gets cast downwards instead.

if (Physics.Raycast(transform.position, transform.forward, out var hit, range))
{
Debug.Log(hit.transform.name);
}

Debug.DrawRay(transform.position, transform.forward * 50, Color.green);


What's wrong with my code?

• Can you select your object and show us what it looks like in the scene view with the translation gizmo visible, in Pivot/Local mode? This will let us see which direction the object's forward vector (blue arrow) points, and compare it to the ray being drawn. – DMGregory Feb 1 at 21:37
• transform.forward will use the GameObject's local forward direction. I'm guessing you're expecting the Ray to go into the Global's forward direction. – atalantus Feb 1 at 21:53
• Don't forget to put your transform gizmo in local mode, as requested. Without this, it only shows you the global axes, not the object's local axes. – DMGregory Feb 2 at 12:40

## 1 Answer

Currently your raycasting happens relative to your transform. Your transform is currently rotated so "forward" is now pointing downwards. If you want your raycasting to happens relative to the global space, you could can change your code to use Vector3.forward instead. I have also changed your hard coded 50 to range so that it will draw your debug ray the same distance as the actual physics ray.

    if (Physics.Raycast(transform.position, Vector3.forward, out var hit, range))
{
Debug.Log(hit.transform.name);
}

Debug.DrawRay(transform.position, Vector3.forward * range, Color.green);


If you want to visually see what the ray hits, you could change your code like this:

    if (Physics.Raycast(transform.position, Vector3.forward, out var hit, range))
{
Debug.Log(hit.transform.name);
Debug.DrawLine(transform.position, hit.point, Color.green);
}
else
{
Debug.DrawRay(transform.position, Vector3.forward * range, Color.red);
}


The last code snippet will draw a red line when it missed the target and a green line to (not through) the target when it got hit.