Shooting mechanics

Here is the script for the basic shooting mechanic. In this script, when the player presses the left click on their mouse, a bullet clone is made which uses the instantiate function to create a clone of the bullet prefab. The bullet is created at the position and rotation of the firePos variable which determines the cloned bullets position and rotation. Next I created a variable for the Rigidbody2D component to access velocity which is how the bullet will move. Finally I created a Vector3 variable called direction which accesses which the rotation values of the bullet which is then given velocity by the bulletRigid variable. The velocity moves the bullet forward depending on which way it is facing.

The next time I worked on this project, I tidied up the variables by adding headers which organises the variables into different sections on the inspector.

To prevent the player from shooting bullets at a fast fire rate, I added a bool variable called can shoot and 2 floats called bulletTimer and maxTime. when the player shoots a bullet, canShoot is set to false which prevents them from firing again. If canShoot is false, bulletTimer counts down to 0 which then allows the player to shoot again and the timer is reset according to maxTime's value.

This makes this script reusable and customizable for different weapons in the game such as machine guns as the timer can be changed which basically changes the fire rate of the gun.