Unity 2D: Help with Block & Parry Mechanic

Hello! I am trying to implement a blocking and parrying mechanic in my game and I am having some trouble with it. The goal is to have the following:

  • Player presses a key and begins blocking
  • For a few frames after they press the key, any attacks that hit them will be ‘parried’ and no damage will be dealt
  • If any attacks hit them after the parry window is ended but while they are still holding down the block key, they are still blocking and only half the damage is dealt
  • While the player holds down the blocking input, they will continue to block until they release it.

The challenges I am encountering are two-fold:

  • Implementing the parrying window for a set amount of time
  • Making it to so the player can’t just spam the block button over and over to get a parry

The code below works as is, but the problem is that the parryWindowTimer seems to decrement immediately no matter how high I set it. I need the window to last only for a set amount of frames or time.

The other problem is that currently if the player releases the block key and immediately presses it again, they get a fresh parryWindowTimer, meaning that they can just spam the block input over and over without consequence. I’d like to decrease the parryWindowTimer if they attempt to block again after a certain amount of time. For example, if they try to block again immediately after releasing the block input, the parryWindowTimer is now only 0.1 seconds instead of 0.3 seconds (just an example, not actual numbers).

Any help would be greatly appreciated!

Here is my code so far:

    [SerializeField] bool playerIsBlocking;
    [SerializeField] float parryWindowTimer = 100.0f;
    [SerializeField] bool playerIsParrying;

    public void BlockAndParry(InputAction.CallbackContext context)
    {
        if (context.started && !playerIsAttacking && !playerIsRolling && !playerIsJumping)
        {
            StartCoroutine(PlayerBlockAndParry());
        }
        else
        {
            return;
        }
    }

    IEnumerator PlayerBlockAndParry()
    {
        playerIsBlocking = true;
        playerIsParrying = true;
        playerMoveSpeed = 3.5f;

        while (playerIsBlocking = true && parryWindowTimer > Mathf.Epsilon)
        {
            parryWindowTimer -= Time.deltaTime;
        }

        playerIsParrying = false;
        yield break;
    }

    public void EndBlockAndParry(InputAction.CallbackContext context)
    {
        if (context.canceled && !playerIsAttacking && !playerIsRolling && !playerIsJumping)
        {
            playerIsBlocking = false;
            parryWindowTimer = 100.0f;
            playerMoveSpeed = 7.0f;
        }
        else
        {
            return;
        }
    }

Please don’t use the 2D physics tag unless you’re asking about 2D physics.

Thanks.

Sorry, I have removed that.

It might prove helpful to scribble out an actual flowchart of conditions.

Generally these things can be captured as a simple state change for each actor:

  • some of the state changes are player driven (idle into attack, idle to blocking, etc)

  • some of them can only be triggered during certain time windows (blocking, then parrying) (OR they trigger differently… eg, block opens the possibility of parry for a short window)

  • some of them auto-trigger (eg, attack returning to idle)

I personally find it easiest to just use a float to track small windows of time like this, adjusting the variable by Time.deltaTime each frame.

I use this timer approach all over my games and it is very easy to debug and reason about simply by printing out the value of the timer.

Hi Kurt,

Thanks for your reply! Your approach is a great idea and I will begin mapping out on paper the different states I have and what triggers them.

Can I just ask about what you said regarding your timer - I feel like this is what I have tried to do above in my code using the float parryWindowTimer, but the timer seems to just decrement immediately all the way down to zero? I have had a lot of success using WaitForSeconds to cause a delay as that seems to use actual seconds, but in this case I cannot use WaitForSeconds. Can you explain how I can have a timer count down in my while loop by a set amount of time chosen by me?

Ah yes, looking at your code you don’t yield inside that while loop.

That’s why it appears to instantly go to zero. It’s doing it one thing at a time, but you aren’t getting a chance to see it.

Here’s why… here’s the skinny:

Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

Nothing will render, no input will be processed, no Debug.Log() will come out, no GameObjects or transforms will appear to update.

Absolutely NOTHING will happen… until your code either:

  • returns from whatever function it is running

  • yields from whatever coroutine it is running

As long as your code is looping, Unity isn’t going to do even a single frame of change. Nothing.

No exceptions.

“Yield early, yield often, yield like your game depends on it… it does!” - Kurt Dekker

Hi Kurt. Thanks again for your response. Sorry I don’t think I understand what you mean. The code runs just fine - it goes through without issue and the while loop executes based upon the conditions I’ve given it.

Anything I put inside the while loop (like a Debug.Log) work fine as well. It’s just that the parryWindowTimer zooms down to 0, no matter what value I set the float to.

Can you explain how I need to include a yield to make it work? How do I ensure the while loop runs only for a specified amount of time? I thought it would work with the parryWindowTimer and decrementing it by Time.deltaTime but that doesn’t seem to be working :frowning:

For that, add more variables and use math.

To have weaker parries when you repeat them quickly, create a new variable “parryEnergy”. Whenever they stop parrying, subtract the actual parry time from parryEnergy. When they could parry but don’t, add a little. It’s like an invisible energy bar. The effect of it is: Full = parry for the max time, half = parry for half the max time, and so on – the math is parryWindowTimer=100.0f*(parryEnergy/maxParryEnergy). Play around with the maximum, how fast it fills up, and the formula to compute max parry time to make it feel right.

It seems as if you could also use a parryDelay variable to avoid spamming parries. Normally when they stop parrying, set the delay to like 10, and they can’t parry until it counts down to 0. For fun, you could add extra delay for how much missing parryEnergy they have – maybe if parryEnergy is at half then the parryDelay starts at 15 (more math, like parryDelay=10+10*(maxParryEnergy-parryEnergy)/maxParryEnergy). Or maybe that only kicks in once it falls below half energy. For that matter, maybe they can parry faster as energy gets low.

Maybe a loophole in that system is making short, perfectly-timed parries which barely reduce the energy. To fix that, you could make another variable “parryDelayCost” which ignores the length of a parry – add a flat # whenever a parry starts, and subtract a little when not parrying. So it jumps up quickly for lots of micro parries. Use that to compute the delay between parries (instead of the old parryEnergy, which still limits length of parries). That seems pretty complex, but it’s not so bad when your full parry system is working and you just want to fix one little problem by adding one more variable which goes up and down with the rules you want and is added to one formula.

Thanks folks. I’ve managed to get everything working with the intended functionality. Here is the code if interested:

    public void BlockAndParry(InputAction.CallbackContext context)
    {
        if (context.started && !playerIsAttacking && !playerIsRolling && !playerIsJumping)
        {
            StartCoroutine(PlayerBlockAndParry());
        }
        else
        {
            return;
        }
    }

    IEnumerator PlayerBlockAndParry()
    {
        playerIsBlocking = true;
        playerIsParrying = true;
        playerMoveSpeed = 3.5f;

        while (playerIsBlocking == true && parryWindowTimer > Mathf.Epsilon)
        {
            parryWindowTimer -= Time.deltaTime;
            yield return null;
        }

        playerIsParrying = false;

        yield break;
    }

    public void EndBlockAndParry(InputAction.CallbackContext context)
    {
        if (context.canceled && !playerIsAttacking && !playerIsRolling && !playerIsJumping)
        {
            playerIsBlocking = false;
            parryWindowTimer = parryWindowShort;
            playerMoveSpeed = 7.0f;
            StartCoroutine(ParryDelayFunction());
        }
        else
        {
            return;
        }
    }

    IEnumerator ParryDelayFunction()
    {
        while (playerIsBlocking == false && parryDelayTimer >= Mathf.Epsilon)
        {
            parryDelayTimer -= Time.deltaTime;
            yield return null;
        }

        if (parryDelayTimer <= Mathf.Epsilon)
        {
            parryWindowTimer = parryWindowOriginal;
            parryDelayTimer = 1.5f;
        }
        else if (parryDelayTimer > Mathf.Epsilon)
        {
            parryDelayTimer = 1.5f;
        }
    }

    [SerializeField] float parryCooldown;
    IEnumerator PlayerNewBlockAndParry()
    {
        playerIsParrying = true;
        playerCanMove = false;
        playerRB.velocity = new Vector2 (0f,0f);
        playerSprite.color = Color.green;

        yield return new WaitForSeconds(parryCooldown);

        playerSprite.color = Color.white;
        playerIsParrying = false;
        playerCanMove = true;
    }