It came from behind: Firing lasers at player

Objective: Create an enemy that fires a laser at player when the enemy gets behind the player.

Some enemies wait until they get behind the player then fire at the player.

Within the Enemy script, create a new enemy type, _enemyID of 4, that will attack the player from behind . Increasing _enemyID = Random.Range(0, 4) to _enemyID = Random.Range(0, 5) in void Start() creates this new enemy type 20% of the time. In void Update() modify the laser fire to allow an aimed shot, as shown below. After instantiating the enemy laser, the laser needs to point at the player. Since this is 2D game, transform.LookAt or Quternion.LookRotation collapse the collider and are not useable. Instead use the Mathf.Atan2 function to set the rotation of the laser to point toward the player. The actual movement of the laser is handled in the laser script but needs the player location, which is passed from the enemy script using the public AimedLaser() function in the Laser script.

Enemy fire section of void update in the Enemy script.

The AimedLaser() function assigns the target provided by the enemy script, as shown below. The private Vector3 _laserTargetVector is assigned Vector3.up in void Start(), allowing the laser to move up if a player laser and down if an enemy laser. If the laser is aimed this initial value is assigned to a normalized vector towards the players position at the time the laser is fired by the enemy.

AimedLaser function in Laser script

The laser movement script in void Update() must be modified to use this target vector, as shown below, keeping the z axis for this 2D game at zero.

Void Update function in Laser script controlling laser movement

Now the player must keep an eye on their six.

Software engineer