Make enemy face the player when is moving in Unity
The enemy follows the player and faces him.
Objective: Rotate the enemy game object when it is moving towards the player.
In this case I am adding this code in the switch case when the enemy is following the player. First I create 2 Vector3 variables to store the target (the player position) and the enemy position. Then we have to subtract the enemy x and y position to the target x and y position it give us the path we need to calculate the angle.
To calculate the angle we have to use the function Mathf.Atan2() and pass as a parameter the x and y of the target vector and multiply it by the Mathf.Rad2Deg constant to get the angle in degrees.
Next we have to rotate the game object using the function Quaternion.Euler and passing as a parameters 0 for the x and y and the angle minus 180 (we have to subtract 180 to the angle because the enemy is moving down and that is the offset).
Then to make the enemy laser face the same direction in the shoot laser routine we assign the enemy rotation to the instantiated laser.
And good to go!!! Now the enemy faces the player when is moving towards them.