Adventures in GameDev with GameDevHQ — Implementing a cooldown system.
So we’re firing our lasers and we’re going nuts shooting a whole bunch at once, but we need a bit of self control! Let’s just shoot one, wait a little while, and then let the player shoot another one. They may be pressing the fire button a hundred times a second, but our design will only allow them to fire one laser per half second.
So first question is where should we put it, in the laser or player? Well, since the player is doing the actual shooting it would make sense to place the cooldown system there.
We’ll need a few variables, the fire rate which will be every half second, and a canFire variable that holds the amount of time before the player can fire again.
We’ll check the fire button input and we’ll tell unity to also check to be sure if Time.time is larger than the -canFire (which its initial amount is -1 makes it true) then we instantiate.
So now that hitting the firebutton/space and Time.time (let’s say 1) IS larger than _canfire, _canFire is now equal to our current Time with the fire rate of half a second added to it, (_canFire is now equal to 1.5) and the laser is instantiated. Now for the next checks:
Time.time = 1.1, is it larger than _canFire (1.5)? No it isn’t so on to the next moment: Time.time =1.2. Is it larger than 1.5? nope.
Time.time = 1.3, 1.4,1.5…THEN!
is Time.time (1.6) larger than 1.5? (yes!)
Instantiate another laser, then make canfire = current time(1.6) + fire rate (1.6+.5=2.1) No
and on and on we go…let’s test it!
I’m pressing my spacebar like there’s no tomorrow and it isn’t like yesterday. There’s only a limited amount of lasers being instantiated now, just how we planned it. This is a bit too slow, so we’ll just change it to .15 in the editor window and try it.
Ahhhhh! That’s more reasonable!
Ok, that’s it for now. Tomorrow we’ll get into physics!