We have our Player cube firing some Lasers, but the problem is that they can fire as many lasers as they can. Seems a little unfair to our Enemies we’ll eventually be spawning.
The best way to counteract this and make the game more challenging is to add a cooldown system for firing a laser!
Adding a Cooldown
Adding a cooldown to our Player’s firing mechanism isn’t that difficult, however the concept may be a little hard to wrap your head around at first.
The first concept we need to understand is Time.time.
Time.time is the amount of time, in seconds, that the application (or game in our case) has been running for. If our game was running for 5 seconds, Time.time = 5.0f.
The next thing to understand is our canFire variable.
This will be a float value we compare against Time.time. In our system, the Player can only fire a laser when the Space key is pressed AND Time.time is greater than canFire.
Our canFire is set to -1f, so that the Player can immediately begin firing. Since Time.time only goes in the positive direction, it’s starting point of 0 is automatically greater than our canFire of -1.
And lastly our fireRate.
This is the amount of time we want our firing cooldown to be. In this system it is set for 0.3f. So we want to be able to fire every 0.3 seconds.
Here is our system in code:
Why it works
Since the Player can only fire when Space is pressed and Time.time is greater than canFire, we have to keep adjusting canFire, or else the Player could fire rapidly — not utilizing a cooldown.
Each time the Player fires, we adjust the canFire rate by giving it the value of Time.time + fireRate.
This ensures that the Player has to wait for the fireRate time value before firing again.
The player fires once the game begins, when Time.time = 1f.
canFire is adjusted and now equals 1.3f (Time.time + fireRate of 0.3f).
Time.time which is still 1, is no longer greater than canFire, and the Player cannot fire again since the conditions are not met.
Only after a time of 1.3 seconds since the beginning of the game can the Player fire again.
Hopefully this makes sense. It’s a fairly simple cooldown system, and can get much more complex, but for the time being we do not need it to be. It suits our needs just fine.
Below is just some code cleanup now that our functionality is working how we want it. Created a FireLaser() function and moved our firing method inside.