Wrong angle in raycast

Hello everyone !

I am currently trying to create a game and I want the enemy to follow the player when spotted.
To do this, I have a 3 step process :

  • I create a variable that contains the angle beetween the player and the enemy
  • I make sure that this angle is in the angle of view of the enemy
  • If it’s true, I create a Raycast and I make sur that the hit collider is my player

The problem is that the angle seems ok when I look at the Debug Raycast
but it seems that it doesn’t detect the plyer, it detects the walls and all, but not the player.

I made sure the it wasn’t the collider that was at fault, but when I change angle for “transform.forward”, the player is detected successfully.

I have to admit, i don’t know what I did wrong and I hope you’ll see the problem.

here is the code :

               Vector3 angleToPlayer = (player.GetComponent<Collider>().transform.position - transform.position).normalized;

                Debug.Log("angleToPlayer : " + angleToPlayer + " forward : " + transform.forward);

                Debug.DrawRay(transform.position, transform.forward * ViewRange, Color.red);
                Debug.DrawRay(transform.position, angleToPlayer * ViewRange, Color.blue);


                if (angleToPlayer.y > -AngleOfView / 2 && angleToPlayer.y < AngleOfView / 2)
                {
                    RaycastHit hit;
                    if (Physics.Raycast(transform.position, angleToPlayer, out hit, ViewRange))
                    {
                        if (hit.collider.gameObject.tag == "Player")
                        {
                            Debug.Log("Player found");
                            state = "Chasing";

                        }
                        //Debug.Log("hit tag : " + hit.collider.gameObject.tag);

                    }
                }

Thanks in advance !

Ok so I know what was the problem, it seems that the y element of the Vector wasn’t helping, I just set it to 0 and now it works !