Adjusting the rate of fire in Unity.
Shooting bullets at the speed of, slower than my hands.
Now, a game gives you a gun or some kind of weapon and how fast does it usually let you attack with the weapon? Most of the time, not as fast as you humanly can. There is usually a cooldown before you can attack again, no matter how short it may be. I needed to create this as my current laser that I just made before, shoots as fast as my hands can smash that space bar.
Definitely wouldn't be fair for the enemies would it?
So how do we do this?
Well, as always we have to make Variables. One for my fire rate, another for a time of being able to actually fire. We will get to that in just a moment.
In my shooting code from before, I added in the if statement another requirement using && for if Time.time (Which is the current games running time) is greater than the _canFire variable. (Which at the moment is -1 at start). So when the game starts, whatever seconds the game may have run for, the first time I hit the space bar, Time will be greater than _canFire.
However every time this code is successfully called, I made it so that _canFire changes to the current Time.time + _fireRate, effectively increasing the _canFire as we shoot.
With this I can limit the firing amount of a player and well here is how it looks.
It could use some adjustment but we can easily just change our variable in either the inspector or the script itself.
Remember, limitations are what makes things interesting in games. You can’t have the player be too strong right? Unless it’s a game about that at least.
See you again in the next article!