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.
To fix this, we need to “flip” the scale of whole gameobject instead of flip the sprite.
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.
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.