My journey becoming a Unity game developer: Laser prototype for Galaxy Invaders pt.2
Objective: Create an offset position to have the Laser shoot from the Player without touching the Player object. Also, implement a delay between each laser fired to prevent the Player from overloading the screen with lasers using a Coroutine.
We need to create an offset position for the lasers each time the player shoots to prevent the lasers from coming out of the Player’s body, and colliding with the Player object. This can look weird to the user playing the game seeing lasers coming out of their body. Plus, lasers killing the Player itself every time they shoot will make this game unplayable.
To fix this issue, let’s take the Laser prefab and find the position for it slightly above the Player where the Laser and Player objects are not touching. Once we’re satisfied with the position of Laser above the Player, copy the Laser’s Y-axis value as we will use this in our code to position it as the starting point to shoot out from the Player using Instantiation.
In the PlayerBehavior script, add a new Vector3 offset to the transform position in the Instantiate() method. In the new Vector3 Y-axis position, use the value copied from the Laser’s offset position we settled on which was 0.8f for when the Laser was completely off the screen.
Playing the game, we see the lasers are instantiating at 0.8f above the Player object, thus avoiding any conflicts between the Laser and Player objects.
Now we have to fix another problem which is the Player ability to shoot lasers in rapid fire. We’re going to create a time delay between each laser fired.
Back in the PlayerBehavior script, create a new variable Type Bool name canFire. The Access Modifier security level will be set to Private, but I’m going to use the SerializeField attribute for demonstration purposes.
Then, in the Start() function, set the canFire variable to True as this will allow the Player the ability to shoot a laser at the beginning of gameplay.
In the Update() function, right after the Laser is instantiated when the Space Bar key is pressed, we want to set canFire variable to False to prevent the player from shooting again. After that we want to Start a Coroutine for the LaserDelay() IEnumerator that we must create.
Create a Private Type IEnumerator name LaserDelay() to handle the delay between laser shots. First statement inside LaserDelay() will be to pause or Yield, then Return a result of waiting for 0.3 seconds before setting canFire to True again.
Lasers are now shooting at 0.3 seconds per shot from the Player.
We should optimize our code inside the IF statements by selecting all the code, cutting it out, and placing it into a new method name FireLaser(). FireLaser() method will activate when the Space Bar key is pressed & canFire is True.
Lasers shooting out at 0.3 seconds in front of the Player object with no issues.