Feature: Rear Firing Enemy

This article will make an Enemy that fires from the rear when it has passed the Player on the screen. This script will inherit from the Abstract Class that we converted the Enemy script to in the previous article.

The first thing we need to do is give the new Enemy Prefab a second point to spawn the rear Laser.

In the RearFireEnemy script, we need two variables. The first is for the Transform that the rear Laser will spawn. The second is bool, so the script will know when the Player is behind the Enemy and fire the Laser from the rear of the ship.

Next, we need a method to determine if the Player is below or above the Enemy. We need two local float variables in the method, one for the Player’s y-axis value and the second for the Enemy’s y-axis value. Then create an if statement to check if the playerYAxis is greater than the enemyYAxis. If so, the Player is behind the Enemy, and if not, the Player is in front of the Enemy.

Then we will call the DeterminePlayerPosition method in the overridden Start after Start on the Enemy script has run, and on the overridden Update before Update on the Enemy script has run so that it will know if it needs to change the spawn location.

We need to override the FireLaser method and add an if statement that checks if _isPlayerBehind is false. If so, then have the FireLaser method run normally. For everything else, we will use the Fire logic from the Enemy script but have it instantiate the Laser Prefab at the rear spawn point and not tell the Laser to change which direction it moves in.

Depending on where the Player is, the Enemy will change where it fires from on the Enemy.

Unity Developer, Software Engineer, Game Designer