Enemies Straight Ahead!
Now that our Laser is working and balanced, we can add enemies to our game so our Player has something to fire at. Today we will create an Enemy GameObject and implement Enemy behavior.
So the first step to creating our Enemy is to create a GameObject.
Then we create an Enemy Material and add it to our Enemy GameObject.
Lastly, let’s turn the Enemy GameObject into an Enemy Prefab because we want multiple enemies to appear in our game.
Now we have an Enemy Prefab!
Now that an Enemy has appeared, we want it to do something. Let’s implement Enemy Behavior by creating an Enemy Script.
Let’s spawn our enemy at the top so our Player has time to react and fire at the enemy.
- To set a spawn point, we set the GameObject’s position in the Start function
- The Start function is called right when the game starts
Now, the Enemy should move down towards the Player to give the Player a challenge.
Alright, now the Enemy spawns at the top and goes down towards our Player. Let’s try it out.
Nice! It works, but after the Enemy leaves the screen, they just disappear forever. Let’s add a respawn mechanic so after the Enemy leaves the screen, they will respawn at the top.
Rundown of code:
- if statement is checking when the Enemy leaves the screen by tracking the ‘y’ position of the GameObject
- randomX variable is getting a random number between -9 and 9 so the Enemy can respawn at a random ‘x’ position on the screen
- transform.position is setting the Enemy’s new position after it leaves the screen, using a random ‘x’ value and 8 for the ‘y’ value so the Enemy reappears at the top
Let’s test out our game!
Nice, it works! Our enemy now reappears at the top after it leaves the screen. Thanks for reading!