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.




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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

My journey to the cloud

Setup https for nginx on AWS EC2 Linux Instance using docker + certbot(Lets Encrypt)

Why Is End-to-End Tracing Important For Serverless

Copy past python virtual environment from one machine to another.

If You Want to Learn Programming, These are the Languages You Should Consider Learning

New Way of Hashing Data In .NET 5 and Later

A Cooldown System- Game Dev Series 07

RSCSS  — Styling your CSS without losing your sanity

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.

More from Medium

What is a Control Track in Timeline

Magnetism in Unity Made Easy!

Unity camera plugin save image data as bytes

Adding a burst laser powerup