Nothing can lead to boredom quicker than making a game too easy to play. If you’re making any kind of shooter and give the player the ability to create a literal wall of bullets then you will soon find them moving on to better gaming experiences.
Limit the speed at which a player can fire projectiles.
Let’s start by taking a look at what a basic script might look like for shooting “bullets” from our player Object.
In this simple example, our Player class has two variables: a
float called ‘Speed’ and a
GameObject called ‘BulletPrefab’.
Update() Method we have some code to move our player
GameObject and we also look for player input in the form of the Spacebar. Once the Spacebar is pressed, we instantiate a
The problem is that in order to retrieve player input, we have to look for it in
Update(). Update, as we know, can run upwards of 60 times per second or more — meaning that if our player is physically able to press the Spacebar that many times per second, they will shoot out as many bullets. So what to do, what to do?
Unity gives us a way of getting a value in seconds of how much time has passed from the start of the game. This value is constantly increasing in real-time. Let’s take advantage of it to limit the speed at which our player fires their weapon.
- First we will create 3 variables to control this desired behavior.
bool CanShootwill be the basis for controlling when the player is allowed to shoot.
- We will control how often this can happen with the
- Finally we will use our
float NextShotto keep track of when we can set the player’s ability to shoot again to
In this bit of code we check to see if the value of
Time.time is greater than the value of
NextShot . If this condition returns true, then we can give the player the chance to shoot again by setting our
bool CanShoot to true.
Once we have our
bool in place, we can use it in our if statement where we look for player input as a second condition that must be met before allowing the player to instantiate a bullet.
When that happens you will note that we immediately reset our
float NextShot to be equal to the sum of our
float FireRate and the current value of
Time.time . In this way we can slow down the rate at which the player can shoot bullets regardless of how fast they can press the Spacebar.
The final code looks like this:
We now have full control of how fast the player can fire their weapon and we also have the ability of tweaking this value in our inspector to achieve the desired effect. By creating variables to hold all of these values we also allow ourselves the possibility of changing them at runtime through code thus creating a more modular and flexible system.