0
\$\begingroup\$

I am having trouble executing a raycast to check if there is anything between the player sprite and a second sprite. This is my code :

    void Start () {

        play1 = GameObject.Find("player");
        game1 = GameObject.Find("lightidle_0");
    }

    // Update is called once per frame
    void Update () {

        Vector3 playpos = play1.transform.position;
        Vector3 gamepos = game1.transform.position;
        Vector3 defvector = new Vector3 (1, 0, 0);

        Ray playray= new Ray (playpos, defvector);

        float distance = playpos.x - gamepos.x;

        if (distance > 0) {
            Debug.Log (Physics.Raycast(playray,distance));
        }
        else {  defvector = -defvector;
Debug.Log (Physics.Raycast(playray,distance));
}

So supposedly, if there is anything between both objects, Raycast should return true. But it is always stuck on false, I have debugged, and tried everything, its value never changes, no matter where both objects are located, I added 2 huge colliders on both sides of the scene and it still outputs false.

I also added a Debug.DrawRay (playpos, defvector * distance); but the ray isn't drawn at all, so it means that is the reason of the error, but why? I can't figure it out.

\$\endgroup\$
0
\$\begingroup\$

I don't quite know what was the problem here, but as a fix i changed the Physics.Raycast command to

Physics2D.Linecast(startposition, endposition);

This fixed the problem. I also made 2 new objects childs of the player, and the npc, and fixed it all up.

Reference to how I did it all in this video : https://www.youtube.com/watch?v=cJj7-Sy03HQ

\$\endgroup\$
-1
\$\begingroup\$

tried:

Physics.Raycast(playpos ,playpos - gamepos,  (playpos - gamepos).magnitude)

or

Physics.Raycast(playpos ,gamepos-playpos ,  (gamepos -playpos ).magnitude)

?

plus keep in mind: "Raycasts will not detect colliders for which the raycast origin is inside the collider"

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .