Creating Waves of Enemies
Objective: Implement wave sequencing of enemies, with more enemies coming each wave.
Here’s a bit more specifics on the behavior we want:
- Wave begins with UI text displaying the wave number
- Enemies should gradually appear over some amount of time
- Wave ends when all enemies have been instantiated AND are destroyed by the player
- When the previous wave ends, next wave begins after a short time
- Each new wave has more enemies than the last
First we need to make some adjustments to SpawnManager. Importantly, we need a way to keep track of what enemies are alive, so that we know when all the enemies in a wave have been destroyed. We can use a List to do this. In this case, it’s better than an array because it provides some useful functions for removing enemies and determining if it is empty.
The core of all this is a coroutine that makes the enemies gradually appear. First, we determine the numbers of enemies to create, and the amount of time that we should wait in between enemy spawns. Then, while we haven’t yet created all the enemies yet, it will wait that amount of time and then create a new enemy. We also make sure that enemy is added to the list, and keep track of how many enemies we’ve created so far. Once we’ve created the required number of enemies, the while loop and the coroutine both end.
This coroutine should be started for the first time, when the asteroid is destroyed at the beginning of the game. The wave number is also set to 1 at that time.
We also want the spawn manager to be aware when enemies die, and remove them from the list. When the list is empty and all enemies have been created, that means the player has successfully destroyed all the enemies in the wave, so the next wave should start.
Here’s an example of a wave of 10 enemies appearing every once every half a second. Things get dicey very quickly!
The last part we need is a UI element that declares that the wave is starting, and what wave the player is on. For this, I decided to try something a bit fancy and have the text smoothly change color over time.
First, when the SpawnManager starts a wave, it notifies the UI Manager to update the text, activate it, and slowly increase the text’s alpha value over time. This causes the text it to fade in rather than appearing instantly.
Next, the coroutine create a sine squared wave that smoothly changes between 0 and 1, and use that value to determine what color the text will be by linear interpolation. This will change the text’s color gradually back and forth over time.
Finally, we fade out the text by doing the first step in reverse, changing the text alpha back to zero over time.
Here’s the end result. It’s a very nice way to declare the wave without being too intrusive.