Prototype: Attack Cooldown

Introduction

Our player can attack, which is great, but we don’t have a cooldown time between attacks, which would make our game incredibly easy if we fire as fast as we can hit the fire key.

We’ll take care of that in this post.

The Challenge

Our challenge is to introduce a cooldown timer that will allow anyone on our team to modify the minimum amount of time a player must wait before being able to fire subsequent projectiles. Let’s get started!

Tracking Time Elapsed

There are multiple ways to solve any problem, and this is no exception. For our prototype, I’m going to implement the cooldown mechanic using Time.time and a time elapsed field that will store the next time that the player will be able to attack. Let’s break it down, step by step.

First, we need a variable to store the duration of time before the player can shoot after. This is our cooldown time that will have the SerializeField attribute so we can easily change it during playtesting. I’ll name this _attackCooldownTime.

Next, we need a variable that will store the sum of Time.time and our cooldown time variable. I’ll name this _attackCooldownTimeElapsed for consistency and initialize this value to -1 because otherwise we will have to wait for our cooldown time before we can attack for the first time.

Cooldown Fields

Now that we have these two variables, we can add more criteria to our attack condition. We now want to check if Time.time has since surpassed the _cooldownTimeElapsed when the player hits the space bar to fire.

When we’re able to fire, we’ll set the _cooldownTimeElapsed to the sum of Time.time and _cooldownTime so that we set it to be the current time plus our cooldown duration.

Cooldown Condition Implementation

Just for demonstration purposes, I’ll set the attack cooldown time in the inspector to 2 so you can see that even when I am spamming the space bar, I can only fire once every 2 seconds.

Attack Every Two Seconds

Summary

With that in place, we now have an attack cooldown mechanic that can easily be modified by anybody on the team with no coding required.

Stay tuned for the next post.
Take care.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s