99 Problems and A New Enemy is One

In this article I am going to talk about adding a new enemy with a different behavior. This enemy’s behavior is a simple one, which has it moving either left or right across the screen. The enemy will also fire at random intervals.

I created a 2D sprite and import the image and rename this gameObject Enemy 2. A Rigidbody 2D, Box Collider 2D, AudioSource and a new Script to Enemy 2. The hardest part of this code was creating a way for the Enemy to either start on the left side of screen and move across to the right or start on the right side of the screen and move across going left.

I needed to randomize a boolean to determine whether the Enemy will start on the left side or the right side. This cannot be done with your traditional boolean of true or false. So, we will use an integer (0 or 1) in replacement of the true or false.

This start position will be randomized so it will be either 0 or 1.

If 0 is picked, we will set the position to left side of the screen and if it is 1 it will start on the right side of the screen. The Y is a random range is between the top of the screen to about the middle of screen.

Once the starting position is set, we will need to move the Enemy across the screen but depending on what side of the screen it is on will determine the direction it will move. We need to track this, so a boolean is created (_isMovingRight) and when position is set, if it is on the left side _isMovingRight will be set to true and if it starts on the right side _isMovingRight will be set to false. We can use this boolean to determine if it needs to move right or left. If _isMovingRight is true will set the translate to go right and Else the Enemy will translate left.

As the enemy moves off the screen they will continue to move that direction FOREVER and we do not want this because it will eat away at the performance of the game. Once the Enemy passes the x position of -11 or 11, it will be destroyed. This gives a different movement compared to Enemy 1, which moves from top of the screen to the bottom. The rest of the behavior is the same, so I will not cover the shooting aspect since I covered it in a previous article. I plan on creating more enemies with different behaviors and abilities.