2D Shooter: Moving the Laser and Destroying It

Sabrina Windsor
2 min readMay 23, 2021

--

Now that we have the laser made, we want it to act like a laser. Instead of programming its behavior in the player script, let’s make a separate script for the laser prefab.

Do this the same way you did for the player script, except drag the created script onto the laser prefab.

Now to make it move when its fired, we need to tell the script to translate the object up. Since we want it to move on its own, we don’t need to worry about inputs like we did for the player. We will still need a speed variable, but everything else is practically the same.

I [SerializeField] my speed variable, assigned it as a float, and gave it a value of 12.5f.

In the update method, the code to get it to move will look like this:

Now we have a laser that moves upward whenever it is instantiated.

But whenever that happens, a new object is created. Eventually, all the objects will add up and crowd the hierarchy and could even affect performance down the road if we don’t do anything. So let’s get rid of this issue altogether by destroying the laser once is passes a certain point in the play field.

The moment where it goes off screen is around 8 on the Y-axis.

Now let’s destroy it by using an if statement. This one is quite straightforward.

Destroy is an awesome word!

Now we have a moving laser that won’t travel endlessly into space!

--

--

Sabrina Windsor

Currently learning to code with the help of GamedevHQ in order to someday my my game ideas come to life!