For the past week I have been creating a rifle controller which contains both shooting and reloading for the rifle. The rifle can be shot by pressing the left mouse button, however they can only shoot once until they reload the rifle bolt using the arrow keys in a sequence (Left, Down, Up, Right).

Rifle shooting


Fig 1: Variables used for the gun shooting

So far the rifle will shoot only one bullet and then the player must reload the rifle bolt. This is controlled by a Boolean which must be checked to true to allow the player to shoot and, once they do shoot, will be set back to false.

The bullet is a prefab which instantiates at the end of the rifle muzzle. The bullet is created as a game object with a rigidbody component which in the script will apply force to the game object’s rigidbody to move the bullet. The bullet speed is set to negative as the bullet would go towards the player if set to a positive number.

The bullet prefab will need a separate script added for what it collides into as well, however in the rifle controller script the bullet will destroy itself after 3 seconds.

Rifle reloading

Fig 2: Variables used for the gun reload

The variables in Fig 2 have been set to public for debugging and so I can take a screenshot of them, however they will be set to private as the reloading works.

The rifle reloading is done by a sequence of key presses to reload the rifle bolt. As shown in Fig 2 and mentioned earlier, the sequence is Left, Down, Up, Right for the arrow keys. Pressing the keys in the wrong order does not progress the reload stage, however in the future I would like to try and make it so pressing the previous key reverses the reload sequence (example: pressing Left and then Right to set the bolt back to its original position).

The sequence index variable counts where the reload sequence currently is. Once it reaches the size limit, the rifle is reloaded, the player can shoot, and the sequence index is set back to 0.

Added crosshair to screen

Fig 3: Aiming crosshair on screen

I also added a crosshair to the middle of the screen. I lined the rifle up so that the bullet travels to where the crosshair is to allow players to accurately shoot at a target when shooting without aiming.

I will still add in aiming down the sights of the rifle to allow a more accurate shot towards a target.

What is next?

I would create a video demonstration of the reloading and shooting of the rifle, however I have not implemented the animations in to the scripts yet. Therefore it is hard to see that the rifle is shooting or reloading unless you can see the variables and debug log.