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.

  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Commented Jul 14, 2019 at 1:04
  • \$\begingroup\$ I haven't but I'd better! Sounds very relevant. \$\endgroup\$
    – DyingIsFun
    Commented Jul 14, 2019 at 1:06

1 Answer 1


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
    // The enemy is close enough that the next step will overshoot
  • \$\begingroup\$ 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. ? \$\endgroup\$
    – DyingIsFun
    Commented Jul 19, 2019 at 3:43
  • \$\begingroup\$ 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. \$\endgroup\$
    – Romen
    Commented Jul 19, 2019 at 14:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .