Journal 42 — Add Enemy in Unity — Smart! Can Fire Backwards

Chris Nielsen
2 min readJun 20, 2021

--

The next challenge I’m writing about is to create a new enemy that can fire backwards if the player moves behind the enemy as the enemy moves down the screen.

To tackle this, first we create a new enemy and script. I will call this enemy Enemy4. I used an asset from Kenney Games imported into Blender, and I recorded an animation from the Object Menu → Quick Effects → Quick Explode.

Blender, new enemy model and quick animation

Enemy4 can inherit the base Enemy class movement.

C# script for Enemy4, inherits base enemy class

However in the Update method, we will also add a reference to a function to check the player’s position.

Enemy4 C# script, check the player position behind the enemy to fire

In this function, we will have a check for two conditions: if the player lines up with the x-position of the enemy, and also that the enemy has moved below the player’s y-position.

From there, we will reference to the Laser C# script to set the type of laser to a backwards type, and we will instantiate another laser prefab to fire at the player with a cooldown to control the rate of fire.

Laser C# script, set backwards laser true and false

As mentioned above, in the Laser C# script, we will update the behavior of the laser, which as you recall either moves up if it’s fired by the player or moves down if fired by the enemy. We need another condition to also fire up towards the player when behind the enemy.

Finally, here are the results of this update. Enjoy!

Unity Playmode with new enemy that can fire backwards

Thank you for your time!

--

--

Chris Nielsen
Chris Nielsen

Written by Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.

No responses yet