Journal 42 — Add Enemy in Unity — Smart! Can Fire Backwards
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.
Enemy4 can inherit the base Enemy class movement.
However in the Update method, we will also add a reference to a function to check the player’s position.
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.
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!
Thank you for your time!