Letting the Enemy Hit Back

Implementing an enemy fire system

Daniel Jennings
3 min readMay 25, 2021

So, we have pretty slick game with random speeds, and spawns, and power ups.

Let’s add a little more challenge by letting the enemy shoot back.

EnemyLaser Prefab

Let’s start by making an EnemyLaser Prefab.

Start with an empty GameObject and add a Laser Prefab to it. Position it inline with the Enemy laser turret. Once it is aligned duplicate and reposition to the duplicate to the other turret. Drag the Enemy Laser to the Prefabs folder to create the Prefab.

Similar to the triple shot Prefab, we will need a method of destroying the EnemyLaser once all of the Lasers are destroyed.

EnemyLaser Prefab Script

The contents of EnemyLaser are identical to TripleShotLaser. Duplicating code is really bad design. Let’s see if we can make this better with a static method.

Which would then turn the call into this.

EnemyLaser Prefab Instantiate

When the Enemy is Instantiated we will call a coroutine to handle laser fire.

Let’s check it out…

That is very odd!! What is going on??

The laser was initially built from the standpoint of the Player. Therefore the default motion is from the Player towards the Enemy, hence the Enemy is attacking itself.

Let’s add a flag (boolean variable) on the laser to store whether the laser belongs to the enemy or player.

We then have to update our Movement method.

And also update our DestroyIfOutOfBounds method.

Collision!!

Great!! We have enemies shooting at us but… we are not taking any damage…

In order to fix this we need a Rigidbody 2D on either the Player or the Laser GameObject. Since manually updating a rigidbody is expensive let’s put it on the laser since it only has a single dimension of motion.

In addition to the Rigidbody we will need an OnTriggerEnter2D method on the Player. We could put it on the laser but we would then need cross script communication which seems overkill for this action.

We now take damage!!

That is exciting but you do have to admit that this is pretty boring… There is no indicator that the Player is taking damage… Let’s fix that with adding an…

Explosion!!

On damage player we need to add some excitement. Good thing we created an explosion Prefab for the asteroid. Let’s see if we can tie into that.

Nice!! That is looking pretty slick!!

--

--