How to tell if the player is facing a enemy

I am trying to add to one of my attack systems a little more but am unable to figure out how to calculate an angle. What I’m trying to do is see if the player is facing towards an enemy at a certain angle, which would enable the player to attack.

So if the player is facing west and the enemy is north of the player, the player will be unable to attack the enemy. So think of it similar to mmorpgs where you have to face a certain angle towards an enemy to be able to attack.

Not sure if this is done with some sort of raycast system, or?

This might help,

*old sample script: Vector3.Dot() · GitHub

1 Like

You just have to calculate the angle between the forward vector of your player and the vector pointing from your player to the enemy :smile:

    myTransform = GetComponent<Transform>();

    // Calculate the vector pointing from the player to the enemy
    Vector3 enemyDir = enemy.position - myTransform.position;

    // Calculate the angle between the forward vector of the player and the vector pointing to the enemy
    float angle = Vector3.Angle(myTransform.forward, enemyDir);

enemy is the GameObject representing the enemy. The script must be attached to your player GameObject

2 Likes