2D Shooter: Cooling Off

The next step in making the laser for this shooter game is to give the laser a cooldown system. This let’s us have control over the fire rate so there is better pacing and consistency within the gameplay. It also will just feel more natural then being able to shoot a pellet so fast that it’s basically a stream of destruction.

First off, let’s open the c# script where we instantiated the laser; this will be the script for “player”. Then we’ll want to create a couple more variables. One will be _fireRate, the other will be _canFire. Both should be private floats, but _fireRate can be accessible in the inspector.

After testing I decided I was happy with _fireRate = .2f, and _canFire = -1f.

The reason we need a variable like _canFire, is because we also need to work with a command called “Time.time” — This command keeps track of how long the game as been in play in seconds. We’ll be using it to compare numbers so we can get the proper fire rate.

Like so:

What I did here is that whenever the game’s play time is greater than the variable _canFire, then and only then the player can activate the laser. Now we’ll be able to activate it right away as -1 will always be less than the current time. Once this happens though, we’ll want to reassign the value.

This is where we make _canFire = Time.time + _fireRate

Let’s say we fired at 5 seconds into playing the game. _canFire will now equal 5.2f. But what if only 5.1 seconds have passed? That would mean Time.time is not greater than _canFire and the if statement would not happen. Only when time played is 5.3 or greater would we finally be able to shoot again.

Now we have a consistent speed of shooting!

Currently learning to code with the help of GamedevHQ in order to someday my my game ideas come to life!