1
\$\begingroup\$

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

downward downwardSceneView

What's wrong with my code?

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Feb 1 at 21:37
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – atalantus Feb 1 at 21:53
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Feb 2 at 12:40
2
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$

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.