0
\$\begingroup\$

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.

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

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
\$\endgroup\$
  • \$\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\$ – GoldenGremlin Jul 19 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 Jul 19 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.