Ray casting in the wrong direcetion

I wanna cast a ray from the computer sprite you see in the background. The ray should detect if theres the player infront of it.

The ray should be casted in the viewers direction. As you can see it isn’t.

In the code, the computer sprite is nonPlayableObject

using UnityEngine;
using DialogueEditor;
public class Actions : MonoBehaviour
{

   


   public void OpenTextbox(GameObject nonPlayableObject)
   {

    
    Debug.Log("Searching for player");

   Debug.DrawLine(nonPlayableObject.transform.position, nonPlayableObject.transform.forward, Color.red, 1);
     if (Physics.Raycast(nonPlayableObject.transform.position, nonPlayableObject.transform.forward, 1))
      { 
           NPCConversation myConversation = nonPlayableObject.transform.GetChild(0).gameObject.GetComponent<NPCConversation>();
            
            ConversationManager.Instance.StartConversation(myConversation);
            Debug.Log("Dialogue started");
         
      }

   }
}

I already tryed using vector3.forward, vector3.up and vector3.back to check whats wrong, but the raycast didn’t change at all.
Additional Info:
Im using an asset from the asset store called “Dialogue Editor”.
The ray is always casted between the computer sprite and -6.5,-7.5, 11

Does anyone have an idea why the ray isnt casted infront of the sprite?

1 Like

Your raycast looks fine. It’s just that you are not drawing correctly. DrawLine expects a start and end position so either you need to calculate the end position as the start position plus the ray direction multiplied by the length or you need to use DrawRay instead.

If you’re not getting the result you expect from the ray cast then you probably want to make sure your layers and colliders are set up correctly. In general I always suggest explicitly passing the layers and the trigger interaction flags to any raycast that way at a glance you always know what to expect.

3 Likes

Your DrawLine call is wrong. DrawLine expects two world space positions, you passed a world space position and a direction vector. So your line will be drawn from your position to one unit away from the world origin (since the direction vector has a length of 1).

You either need to use DrawRay, or when using DrawLine, you have to pass two positions.

var p = nonPlayableObject.transform.position;
Debug.DrawLine(p,p + nonPlayableObject.transform.forward, Color.red, 1);

or

Debug.DrawRay(nonPlayableObject.transform.position, nonPlayableObject.transform.forward, Color.red, 1);

Debugging doesn’t help when you debug the wrong thing :slight_smile:

1 Like

Oh thank you :slight_smile:

1 Like