Shooting lasers

Niklas Bergstrand
4 min readMar 23, 2021

--

A space shooter would not be much of a shooter without lasers, right?
Lets go over a simple implementation of adding projectiles to your game.

First off, we need to create the object that will be our projectile. Right-click on an empty space in the hierarchy and select 3D Object-> Capsule

Rename the object to something suitable like ‘Laser’ and then set the scale to 0.2 on XYZ

Create a folder in the Project window called ‘Prefabs’ and drag the object into that folder. Once the object is in your Prefabs folder it can be removed from the Hierarchy:

Create a new script called ‘Projectile’ and attach to the Laser prefab:

Open the Player script. If you followed my previous article you should have one already in your project. However, these steps can be applied to any game project with a Player script. Add a private GameObject and Vector3. Add the SerializedField attribute to both to ensure they show up in the Inspector:

Select the Player object and drag the Laser prefab to the prefab field and set the Y position to 0.8

In the player script add a new function called Shoot and call it from Update.
Add an if statement in the new function to check if the Space key has been pushed down.

To spawn objects in Unity you use Instantiate() and in our case we will use the version that takes in a prefab, position and rotation. In most instances the rotation should be the default of the prefab. In order to set the default rotation in Unity you use Quaternion.identity. For the position you need to enter the Player transform plus the offset. If you only use the Player position then the projectile will spawn inside the Player object.

Open the Projectile script, add a private variable for speed and set it as serialized to ensure that you can adjust the speed in the Inspector

Create a new function called MoveProjectile() and call it from Update. Inside the MoveProjectile() function add transform.Translate(Vector3.up * _speed * Time.deltaTime). This will move the projectile upwards while active in the scene at the speed you set in the Inspector. As always with anything that is called from Update which is a moving add Time.deltaTime to make it frame independent:

Lastly, to ensure that the scene is not filled up with projectile objects add another function that will destroy the object when it is outside the screen.
In this instance that is roughly 8.0 on the Y axis:

The whole Projectile script:

Good luck!

--

--