Phase II: New Enemy — Mine-Layer
In today’s article, I go over how I added a new enemy that will be a Mine-Layer.
Objective: have an enemy go across the screen from side to side and drop mines that will go down and stop within the player’s area. If the player collides with them, they will explode and damage the player.
This is how our Mine-Layer will look.
I’m going to have the Mine-layer start randomly from either the left side or right side of the screen and also have it start between 1 and 4.5 in the position to give it some variety. I achieve this by creating a SetStartPosition(), which I call from the Start() method.
First, the method sets the y position of the enemy. Then I generate a value for _randomInt that will give a 0 or a 1. If the value is 0, I start the enemy from the left side of the screen. Otherwise, I start the enemy from the right side of the screen.
Next, I do an override for the CalculateMovement() method.
I just created a new prefab for the mines and put it in place of the EnemyLaser prefab for the Mine Layer. So that way, it drops the mines at the same rate it would have fired lasers otherwise.
For the mines, I’ve created a script named MineBehaviour that controls how far the mines move, their collision with the player, and a self-destruct after a certain time.
I use the following variables.
In the Start() method, I set the destination point of the mine. This is the y position where the mine will stop. It is randomized between 0 and -5. I also set the speed of the mine’s decent.
To control the movement, I create a MineMovement() method, which contains the following.
I first check if the mine’s Y position is greater than the destination Y position. If so, I moved down. When it passes the destination position, I set it to that position and call the StartSelfDestruct() coroutine, which I will show below.
This sets a timer between 10 and 20 seconds then runs the DestroyMine() method below.
This method plays the explosion audio, instantiates the explosion prefab, then destroys the game object.
Finally, I use the OnTriggerEnter2D() event to control collision with the player.
If the player collides with the mine, I call the player.Damage() method to the player, then call the DestoyMine() method on the mine.
Below are some examples of how this looks. Also, I’m using a placeholder graphic for the mine.
If the Mine Layer can let off enough mines, it can make moving around a bit difficult for the player while they’re avoiding other enemies and their lasers.
I hope you found this article interesting and until next time, I wish you well on your coding journey.