Cliff Bailey
3 min readJul 11, 2022

Scripting Laser / Projectile Behaviour

As soon as our laser / projectile / object instantiates at the ship tip, it needs to travel up-screen.

First things’ first: create a script in your scripts folder, name it laser, add it to the laser prefab, and open it in Visual Studio.

Here’s what we’re going to cover:

  • instantiate laser from ship tip
  • translate laser in positive direction on y-axis (up the screen)
  • assign a speed variable float of 8 or 9 or…11
  • destroy laser instances after leaving the screen

Here’s our script with a serialized field for the private float _speed and it’s assigned value of 8.9f, and the code for movement straight up in void Update.

Now we just need the coordinate for above screen which we can get by putting our laser prefab in the hierarchy at LocationZero and moving it up the y-axis until it goes out of view on the game screen.

I got 7.24, and will add some units on for safety.

DESTRUCTION

So now we want to destroy each and every laser instance that exceeds 7.29f on the y-axis.

Let’s use the if statement!

And we can punch it in right below our previous code in Update.

SHIP TIP

To get it to spawn right out of the ship’s tip, we’ll need to offset the spawn point a bit.

Make sure your ship and laser prefabs are both at location zero.

Now ease your laser up to a comfortable position and get the coordinate from your inspector.

Prairie-doggin’
In this case we will use a half measure.

We need to make this change in our Player script where the shooting logic is coded.

We’re adding + new Vector3(0, 0.5f, 0), into the code as shown below:

Test it out and adjust as needed.

Tomorrow we’ll implement a cool down system an maybe some more code clean-up.

See you then!