Raining Enemies

Wesley Adams
3 min readApr 16, 2021

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.

Red Enemy setup

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:

  1. Translate the Enemy down in the y-position in real time.
  2. If the Enemy moves off the screen, change its position back to the top of the screen.
  3. 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:

Move Enemy Down

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).

Reset to the Top

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:

Random x-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.

--

--

Wesley Adams

Passionate animator and game developer; Wesley is a co-founder for Multivarious Games and a Creative Director in elearning at Xcelerate Media.