My 90 day journey becoming a Unity game developer: Day-4
Objective: Make the lasers shoot upward; destroy lasers from living in the game infinitely; set the laser’s position to shoot from in front of the player; add a delay between shots fired.
To start, we will create a new script called Laser, and attach it to our Laser Prefab. Create a variable that adds speed to the laser’s movement. Then make the laser shoot in an upward direction inside the Update() function with the following code:
Next, destroy the lasers after reaching 8 units up along the Y-axis on the screen. This is to prevent laser game objects from staying alive in the game until the game stops, and to prevent filling up our Hierarchy. Use the following code inside the Laser script, and inside Update():
Inside the Player script, go to the PlayerMovement() function where we will add an offset to the Player’s laser to shoot from in front of the player, and not from inside the player’s body. This is the following code:
Finally, we will create a cool down to decrease the amount of time in between each laser shot. We must create 2 variables, one for how long we wait between each shot, and the other to determine when we can fire. Then inside our IF condition, check to see if the spacebar has been pressed and if the time we have been playing the game is longer than when we can fire a shot. If time is greater than canFire, adjust the canFire variable to accept the current time plus the fireRate at which we can fire our next shot. The following code will be stored inside the FireLaser() function were it will be called every time the IF condition is valid:
Next time we will start working on the enemy setup.