Adding a Laser Beam to our Laser Enemy — 2D Galaxy Shooter in Unity!

Objective: To add a new firing method to our laser enemy, the laser beam!

Let’s now give our laser enemy a new and improved firing method besides the basic lasers that shoot down the screen. Let’s give the laser enemy a new giant laser beam! Let’s jump into it…

Adding Some Code to “LaserEnemyBehaviour” Script

First we need to make sure that the enemy has a timer for when it can shoot and we will control this through the use of 2 variables, _fireRate and _canFire. Next, we need to create an _enemyMegaLaserOffset variable so that it instantiates directly in front of the enemy. Finally let’s create a serialized Game Object variable that we are going to drag and drop the enemy mega laser prefab into.

Within our Update() method let’s call the LaserEnemyFire() method which we are about to create:

Similar to our Player’s firing mechanism, let’s continually keep checking Time.time and seeing if it is greater than _canFire and if it is then the enemy is going to be allowed to fire. Let’s also make _fireRate equal to a random number between 2 and 4 so that the firing is a bit more random.

Then once Time.time is greater than _canFire, call the MegaLaserFire() method below:

This method is going to handle the instantiation of the _enemyMegaLaserPrefab at it’s transform.position plus an offset and we are going to leave the rotation as it with Quaternion.identity.

Next, we are going to assign the newly instantiated mega laser’s parent to be the ‘Enemy_Laser’ game object.

Finally, we are going to destroy the mega laser after 0.5 seconds.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store