Shooting Laser: improvement

Sudarshan Thube
3 min readNov 9, 2021

--

We created Laser prefab and added Laser script to it which looks like this,

Open Laser script, we need to add code to move Laser upward. now create variable for direction and speed.

Now, we need to setup staring movement for our laser to get that write code in start method, in which we will set the direction upward and write code for movement and with condition that it will destroy after go above certain height in Update function. we will take player maxY, to use variable from player script we need to get reference of player script or make boundary variable static. We will take create reference of player script. now we can access them in enemy script.

We used Time.deltaTime to make laser will move in same speed regardless of speed of CPU speed.

To know more about Time.deltaTime got to this link,

https://docs.unity3d.com/ScriptReference/Time-maximumDeltaTime.html

With code we write our Laser will move upward as soon as it get Spawned.

As we can see laser get spawned, but it looks weird as it get spawned bellow space ship instead of tip of white colored Gun. To fix this we need to add position offset for our lase to Gun point position in Instantiate code. To do that, let’s add variable for gun point position in player script and assign our gun to it, then ad some offset value. Add “Transform” variable name laserGun and float variable name laserOffset. Transform will take only transform value of gun object.

Variable of type transform
Transform of LaserGun object.

Now add code like bellow, which will then spawn laser prefab at desire position.

Run the game and test out our new code.

for more information on Instantiate click here.

We can add some time interval to shooting laser. In our next article we will see how to add interval for shooting laser.

--

--