Phase 2: Erratic Enemy Movement

Objective: Add some movement to the enemy to give some more difficulty to the game

Patterns can be great, specially when they’re easy to follow. At the present when an enemy goes below view they respawn on the same X Axis position but above the screen making it easy to know where the best shot will be. Now what if every 3 seconds they could randomly start sliding down left or right or stay coming straight. It makes it a little more difficult. Go a little further and make the change time random too so that it can be every 2 or 3 seconds it changes, now things get more interesting.

To get this working we will start by creating a private float called sideways and set it to 0 to start. Next create a coroutine to change the sideways value. Call the yield return with a random range wait for seconds of 2 or 3 seconds and then assign the sideways float to a random range between -0.25f and 0.25f.

Sideways coroutine

Start the coroutine in the Start method giving the enemy 2 or 3 seconds going straight down before the sideways movements begin. The enemies won’t be allowed to pass over through the edges to the other side like the player so next, in the calculate movement method run an if and else if statement to check if the enemy passes a certain point on the X axis and set the sideways float to -sideways immediately sending them back in towards the center.

Enemy Movement using a coroutine

In the next post, we will look at creating a new enemy.