Quick background: It’s a 2D game, and I’m trying to get an enemy to detect if the player is on their left or the right, and change facing accordingly. However, enemies aren’t picking up on the facing consistently. Here’s the relevant code:
The “Now facing left/right” message doesn’t fire the instant you swap sides. It’s especially bad when you move over to the enemy’s right side, but other than that, I haven’t been able to find a pattern.
OK, you need to know the angle between the two objects, this will allow you to know where the player is.
Then, you can do whatever you want, in this example, set the correct animation I guess.
I added a Debug.Drawline to see if it was working correctly and also a Debug.Log.
Note the line with if(player) or if(player !=null) with the comment above.
public class test2D : MonoBehaviour {
GameObject player;
Vector2 enemyPos;
Vector2 playerPos;
void Start () {
player = GameObject.Find("Player");
}
void Update () {
//Note that there is no need to find the Gameobject again.
//This will increase performance as finding objects has a big impact.
if (player)
{
playerPos = player.transform.position;
enemyPos = transform.position;
//Angle in radians between the two Gameobjects.
float rawAngle = Mathf.Atan2(enemyPos.y - playerPos.y, enemyPos.x - playerPos.x);
//Mathf.Abs because we only want to know either it is left or right, not up/down.
float angle = Mathf.Abs(rawAngle * Mathf.Rad2Deg);
//Conversion to degrees............^^^^^^^^^^^^^^
Debug.Log(angle);
if (angle < 90f) Debug.Log("FACING LEFT");
else if (angle > 90f) Debug.Log("FACING RIGHT");
Debug.DrawLine(transform.position, player.transform.position,Color.red);
}
}
}
…you are comparing ‘y’ to ‘x’, when you want to compare ‘x’ to ‘x’. In addition, unless you have a separate visual for neither left or right, then the ‘if’ is not necessary at all.