With most shooting games, there is a game mechanic that prevents the player from spamming the shooting button without consequences. Whether it is an ammo count with a reload or time delay between each shot. This encourages the player to think more strategically about shooting and for the player to become more skilled at it.
This is a cool piece of code that uses Time.time, which is the measure of time since the game started in seconds. First, we create two variables.
- _fireRate = time between each shot.
- _fireTime = Time.time (how much time has passed since the start of the game) + _fireRate
Every time the laser is fired, we set a new _fireTime to be equal Time.time + our _fireRate. For example, if we fired 2 seconds into the game, Time.time would be 2 + .5 (our fireRate), making our _fireTime = 2.5
With our _fireTime being equal to 2.5, we can now created a conditional to check for if the Space Bar was pressed AND if Time.time is GREATER THAN our _fireTime of 2.5. The player would have to wait until Time.time gets to 2.6 until they can press the Space Bar to fire again, which will start the whole process over. It is a simple, yet clever piece of code. I am going to be revisiting this to either add an ammo count or status bar for the ammo, with cool down being modified to the player waiting until the reload process is complete before being able to fire again.