As awesome as it may be to fire lasers as fast as you can press the button, you can add difficulty, depth and a dose of reality to your game by implementing a cool-down system.
Objective: Enable time delay between laser fires.
Starting Point: Laser fires from Player object as fast as the Space Key is pressed.
- Set a time delay variable
- Set a time the laser can be fired next
- Check if laser can be fired
- Update time laser can be fired next
Set a time delay variable
To allow the laser to “cool-down” between shots, create a variable to hold the time that should pass before the laser can fire again.
Since the Player object is instantiating the laser, the Player object will also house the logic for when the laser can fire. You can edit the time delay value in the Inspector to suit the feel of your game.
Set a time the laser can be fired next
To determine if the laser can be fired, we will need to store the next time the laser can be fired.
You can initialize this variable with 0f or even -1f if you want to ensure a laser can be fired immediately at the start of game.
Check if laser can be fired
In addition to checking if the Space Key is pressed, you’ll also need to check if the time when the laser is ready has passed before firing the laser. To do this, first you will need to know how long the game has been running. In Unity, Time.time stores the current run-time for the game.
You can compare Time.time to the _laserReady variable to only fire the laser when Time.time is greater than _laserReady.
Update time laser can be fired next
With the code so far, the laser can still be fired as fast as you can hit the Space Key. This is because Time.time increases as the game is played, but _laserReady is still set to its initial value — so runtime is always greater.
To fix this, you’ll need to update _laserReady to the next time the laser can fire. To do this, assign the sum of Time.time and the _laserDelay to _laserReady.
Now, the laser can only be fired every 0.2 seconds, even if you spam the Space Key. Now that’s keeping your lasers cool!