2D Galaxy Shooter — Laser Cool Down System
Today, I am going to go over how to set a cool down system for how fast I can fire my laser. My fire speed now is as fast I can hit the space key and I feel like that can break my game, so lets slow it down!
First thing I need to go over is Time.time. Time.time is just the number of seconds the game has been running, so if we have been playing the game for 90 seconds, Time.time = 90. Seems simple enough!
Now lets make some variables on the player script.
Then, lets head down to Update where we instantiate our laser.
Looking above, this means that if I hit the space key and Time.time is greater than _canFire, then I can fire the laser.
_canFire = Time.time + _fireRate — means that how long the game has been going + _fireRate = _canFire. So if _canFire = 90.15 and Time.Time = 90.0, then we can’t fire, but if Time.time = 90.16, then we can fire.
When we fire, _canFire = current Time.time and can’t be refreshed till Time.time > Time.time + _fireRate and we fire again.
We are now finished with the laser for now, so lets clean up our code.
We don’t really need to clean up the laser script cause that is all the laser does.
In the player script, lets make another method called “void FireLaser()” and cut and paste the inside of our if statement in the new method. Then reference FireLaser() inside the if statement in Update like so.
Now that we are finished with the laser for now, its time to add the enemies!
Thank you for your time!