Projectile & Cool-Down Mechanism

Gert Coppens
4 min readMay 16, 2021

--

In the previous article you are introduced to Pseudocode by the hand of an example for the player to be able to fire a Laser, with a cool-down mechanism. Today, we’ll implement that feature in our code.

First we must create our Laser Prefab. Don’t worry about its graphics, that will be covered in another article.

Create the Laser Prefab

→ Create a new 3D Object Capsule > rename it to ‘Laser’. > Adjust the Transform Scale to (0.1, 0.15, 0.1).

→ Create a new folder in the Project window called “Prefabs” and drag in the Laser to create a Laser Prefab from it so we can reference to it later.

→ Create a new script called ‘Projectile’ and attach it to the Laser Prefab, we will come back to it in a moment.

Modify the Player Script

First we store a reference to our Laser Prefab and create a new Vector3 which is the default position where the Laser will be instantiated.

→ Add a private GameObject and Vector3 variable to the Player script.

In the Inspector while having the Player selected we can now assign the Laser Prefab from our Project Window.

In the Start() function, we set the _projectileSpawnPos as following:

Then we create a new method to instantiate the Laser Prefab if the Space key is pressed.

→ Create a new function called ‘FireProjectile()’.

We Instantiate our Laser Prefab, on the Players transform location + our offset that we declare in start, and at last the rotation of the transform; Quaternion.identity, standing for the initial rotation or “null rotation” of a GameObject.

Cool-Down Mechanic

We must consider that we don’t want the player to be able to spam this mechanic in-game so let’s add cool-down logic to the method. We can do this by introducing Time.time, which is the time of the beginning of this frame.

→ Create a new float type variable to set our rate of fire, as well as an empty float _canFire that we can reference to if we want to know if the player is allowed to Fire or not.

→ Then we modify our FireProjectile() method so that when Space is pressed AND we are allowed to fire, the Laser Prefab will be instantiated.

Allowed to Fire = Time since last frame was called + cool-down rate.

Now if we go back to the Game we can Fire Lasers, but in moderation.

Modify the Projectile Script

What’s left for us to do now is to change the Projectile Behaviour. Much like for the Player, we add a speed variable which we can multiply with a direction and average frames per second in a method called ProjectileMovement().

We also want to destroy the Projectile in a DestroyProjectile() method after moving out of the screen boundaries, so we don’t end up with a pile of projectiles we don’t see or use behind the scenes.

Your script could look like the following.

Previous | Next

--

--

Gert Coppens
Gert Coppens

Written by Gert Coppens

Software Engineer — Unity Game and Application Developer

No responses yet