transform.lookAt not working as intended
I am using transform.LookAt to get an archer to face my player when the player is within attack range. My archer is currently just a cube with an EnemyMovement script on it that includes the below FacePlayer script. The archer also moves with a Nav Mesh Agent.
void FacePlayer()
{
Vector3 targetPosition = new Vector3(
player.position.x,
this.transform.position.y,
player.position.z
);
transform.LookAt(targetPosition);
}
It works perfectly at close distances (let's say up to 5 meters). It also works perfectly when the player is at certain angles to the enemy no matter what distance the player is away (for example at 0 to 150 degrees).
But at certain angles (let's use 150 - 360 degrees based off my working example), the enemy does not face the player correctly at larger distances.
If I am at a distance of 20 meters from the enemy and at an angle of 200 degrees. The enemy is not facing me correctly. But as I start walking closer to the enemy remaining at a 200 degree angle, the enemy starts slowly rotating in my direction until I am 5 meters from the enemy
I can't tell if I am doing something wrong or if this is a bug in unity since I am just using the transform.LookAt function? It almost seems as if the players location is incorrect at larger distances but why would it be working for certain angles and at close range then?
I also attached a file of a rough drawing to help visualize what is going on. The green areas represent the areas where the enemy transform.LookAt is working correctly. The red box is the enemy at the center of the circle