1 If-Statement to Prevent Spamming Attack

Daniele Quero, PhD
Nov 30, 2021 · 3 min read

Objective: code the attack animation and input in order to have a fast enough response and avoid spamming

Once I created the attack animation, as usual, I immediately stumbled upon a problem.

I found that spamming the input for the attack resulted in an interrupted animation, while the particle animation for the slash-effect would continue independently. Not good at all.

At first, I thought about modifying the animation itself, getting rid of the too many frames at the end, when the character returns in the default position. Even if it was a good move, it was not enough.

Let’s think for a moment about what we want here: I want to smash the input key while I’m playing (it’s fun and you know it), without breaking any game mechanics. But still, I don’t want to smash it… for nothing!

Time for state machine behaviour.

The idea is to use a bool, isAttacking , from the main combat class. If the character is attacking then it can attack again until we reset the bool to false.

On entering the state animation, the bool is obviously true but instead of turning it false on exiting, we do it at a certain percentage (trial and error here) of the animation. One way of accessing this percentage is through the animatorStateInfo.normalizedTime property: a float with a value ranging from 0 to 1, so actually a percentage.

When 97.6% of the animation is reached, the bool is again true and we can attack again.

But why this choice?

Well, if you click at a slow enough pace, you will experience no differences.

If try to spam the attack input, you won’t be able to interrupt the current animation until it is almost finished: a good compromise between having to wait for the animation to finish and not having a response at all to our spamming.

If you liked it, clap to it! Check out my games or buy me a coffee: every kind of support is appreciated!!

Geek Culture

Proud to geek out. Follow to join our +1.5M monthly readers.