A Cooldown System- Game Dev Series 07
You cannot shoot the laser unlimited, that is why you need a cooldown system.
Previous: Instantiate & Destroy a Game Object
Although we can fire with space key, there is still got one issue, the firing rate.
It is not quite right if player can fire such rapidly. Therefore, we need a cooldown timer.
The Concept:
We want to make our player to fire with a specific time gap. To do this, we will need to use Time.time
.Time.time
is used for counting time since the game started which we can add some calculation,
We need to set 2 variables. 1 for counting the fire rate, which means the gap time between 2 shots. Another is for current time calculation, this will add the current time and the time gap.
private float _fireRate = 0.2f;
private float _canFire = -1f;
The _fireRate
variable means we have 0.2 second between 2 shots.
The _canFire
is stand for the first time we called this variable, which will be change later.
Then we can add the condition to our if-statement for shooting.
We added && Time.time > _canFire
after our space key detection. Which means only if the player pressed space and the current time is greater than _canFire
time, the Player can fire.
Then we can add another calculation to our firing method.
Added this line above the laser generation code. This means when we pressed space key and shot successfully, the time of _canFire
would be current time plus the time gap that we assign.
At this point, our Player could not fire again since the _canFire
is no longer smaller than Time.time
, even we pressed space key, it would not work.
After 0.2 seconds which is the time we set for _fireRate
, the current time should be greater than _canFire
, and we could fire again!
Here is the result if we play,