Determining the Direction to the player in Unity

Jon Jenkins
2 min readSep 30, 2021

Here you see the skeleton trying to attack the player, but he is not facing the player:

How do we fix this? How can we tell the skeleton what side the player is on and then to turn to face the player? All it takes is some easy vector math.

The player and skeleton both have world positions in the scene. In order to get a vector from one point to another, all we have to do is subtract the starting point from the destination point.

Now all we need to do is look at the x component of direction. This is because we are developing a 2D game that basically only has direction to the left or right.

If the x component is negative then the player is to the left and we need to flip the skeleton’s sprite (setting flip X to true). Note the skeleton starts the level facing right and will move back and forth on its platform. If the x component is positive then we need to set the flip X property to false.

That’s pretty much it on a 2D level using the X and Y axes. Here you can see the finished product:

Now we have a direction from the skeleton (transform.position) to the player. From here all we need to do is look at the x component of the direction vector. If it is negative then we know the player is to the left of the skeleton. If positive then the player is to the right.

--

--

Jon Jenkins

A Unity Developer, interested in all things Unity.