# How to prevent enemies from oscillating left and right during chase?

I have a grounded enemy with a simple chase state. When in this state, the enemy moves with constant vel.x toward the player.

If my player jumps directly above the enemy however, the enemy will quickly flip directions back and forth a few times, since each time the vel.x is updated it flips sign. If the player is on a ladder above the enemy, the enemy will just oscillate back and forth indefinitely. Very ugly.

My enemy does have an engaged state where he pauses and then attacks, but my player has a high jump and so can maintain a far enough distance to avoid triggering the enemy to enter this state.

I am wondering what design choices I can make to prevent this ugly oscillation back and forth during chase.

• Have you looked into the concept of hysteresis? We'll often use this to prevent logic from rapidly flip-flopping when a control value hovers close to its trigger threshold. – DMGregory Jul 14 '19 at 1:04
• I haven't but I'd better! Sounds very relevant. – GrimGrom Jul 14 '19 at 1:06

While your enemy is in their "Chase" state, you can apply a very simple fix.

if (abs(enemy.x - player.x) >= enemy.step_length)
{
// The enemy is at least 1 step away from the player
if (enemy.x > player.x) enemy.x -= enemy.step_length
else if (enemy.x < player.x ) enemy.x += enemy.step_length
}
else
// The enemy is close enough that the next step will overshoot

• But the question is precisely what to do after the final else. For example, should the enemy enter a dedicated wait state, should the enemy remain in the chase state but change to the idle animation, etc. ? – GrimGrom Jul 19 '19 at 3:43
• That is up to you, that's more of a creative decision than a "best practice" thing. I would make an animation for the enemy trying to jump and reach you and play that animation in its own "reaching" state or during this else case in the "chase" state. – Romen Jul 19 '19 at 14:01