Make Your Enemies Facing the Threat- Game Dev Series 114

Objective: add enemies turning to facing Player when when being attacked.

In this article, we would create a function to make enemies turning facing Player when being attacked by them.


In the previous tutorial, we have used flipping sprite on X-axis to make it looks like turning. However, it would cause some issue. When enemy is attacking with flipped sprite, the collider does not flipped at all, and still hitting on the same position.

As you can see the collider is hitting the left side.

To fix this, we need to “flip” the scale of whole gameobject instead of flip the sprite.

Flipping scale

We need to remove the entire “flipX” line and rebuild the function of turning.
Before using scale as turning, we need to get the Player position and send it to enemy as a parameter.

This would return a float number that allows enemy to identify which side that Player is.
And we can use this float in an if statement to make enemy turning around.

And we also need to make sure enemy is in “InCombat” animation state.

Now would be the logic part.
By default, the scale of enemy sprite is positive number when facing right, and negative when facing left. With this, if Player is on the right side of enemy while enemy is walking toward the right side. Then enemy does not need to turning the scale.

On the opposite, when it is walking toward the left side with negative scale. To facing Player who is on the right side, enemy scale needs to multiply -1 on x-axis to face right.

That would make enemy facing Player by turning the whole gameobject, and attacking would be not a problem.

With this logic, when Player is on the left side of enemy would also not be a problem. Just need to fix the timing of multiply -1 on x-axis of scale.

All done! My enemy attacks perfectly every time.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
S.J. Jason Liu

S.J. Jason Liu


A passionate gamer whose goal is to work in video game development.