Spicing up our enemy movement
So, up until now, our enemies spawn at a random horizontal position above the player screen and move straight down at a constant rate.
What I’m going to do is create new ways for enemies to move, and spawn them accordingly.
Modifying our Enemy script
The first thing I want to do is try and think of how I’m going to organize my code around different enemies, with the same script, doing different things.
Simple, I’ll give them IDs.
Done, and to keep me from losing track, I’ve added some comments for what each int value will represent.
My Start() method was starting to get out of hand so I’ve create a new method, DoNullChecks();
That’s much better.
NOTE: The _enemyMoveType = (int)Random.Range(0,1); above should be (int)Random.Range(0,2);
Up until now I’ve directly assigned the _enemyDirection variable when it was declared.
This gave me a large headache before I realized it was a problem.
So we’ll declare it null and assign it in the Start() method.
We use a switch statement to check our randomly assigned _enemyMoveType and set the corresponding _enemyDirection values.
We’ll default to the standard move if for some reason the value is other than expected.
I’ve moved my logic for moving enemy game objects below the player screen back to the top of the screen from the Update() method to its own RespawnAtTop() method.
I’ve moved the moving logic that has been standard so far into MoveStandard() method.
And I’ve add new logic for moving the enemy down and diagonally into MoveDiagonalyDown();
Our Update() method is now much cleaner as we use a switch statement to run the corresponding move type method and call RespawnAtTop() after.
At this point, we have a working enemy spawn that randomly selects a movement type every time the enemy spawns.
To make things more interesting, let’s add a zig zag movement type.
Right now we have a standard, just move down type and a move down and to the right, respawn on left side of screen when off right side of screen.
This new move type will bounce off the horizontal sides all the way until off the bottom of the player screen.
We make a new MoveZigZag() method and check for when it reaches a horizontal bound of the player screen.
When it does, we reverse it’s direction.
Last we add the MoveZigZag(); method call to our switch statement in the Update() method.
Give it a run, have some fun!