Let’s start to talk about Enemies, eh? How about enemies in swarms raining down hellfire down upon thy Player? How about they appear randomly from every far reaches of the dark universe? How about we start with one enemy for now? Cool, let’s begin in this short breakdown of Enemy movements.
Start by making an Enemy cube Prefab. It will be a bit smaller than the Player, will start at the origin position at 0, and need a red material. We can keep this Prefab in the Hierarchy for now.
To add local features of the Enemy, we’ll need to make a new Enemy.cs script. We need to think of some sudo-code of how the Enemy will move:
- Translate the Enemy down in the y-position in real time.
- If the Enemy moves off the screen, change its position back to the top of the screen.
- Upon setting the Enemy back to the top, change its x-position randomly and continue the falling movement.
Just like we did for the Player, we need a private float variable called _speed. Then, in the Update function, we’ll move the y-position in real time down the screen:
Well great! Cool cool cool… but now the Enemy moves down indefinitely and never resets. Well, when the Enemy moves off screen (about -5 meters in the y-position), let’s reset the y-position to the top of the screen (about +7 meters in the y-position).
Hit save and go back to Unity for testing. Press the Play button and you should see our Enemy Boy Wonder move down and respawn to the top of the screen… but in a single file fashion. Hum… wouldn’t it be cooler if we could like randomly spawn the Enemy in any x-position? We can with the Random.Range feature here.
This float value has the following option:
Range(float minInclusive, float maxInclusive);
So let’s setup our screen width range min and max value or left and right range. They are -8 and +8. Then, let’s make a new float in our if-statement and replace that in our x-value of the translation position:
And that’s all you need to randomly get your Enemy to fall down the screen randomly. This is just a start of course. Stay tuned for more articles on enemies.