Phase 2: New Enemy Movement

Dominique Dos Santos
Nerd For Tech
Published in
3 min readMay 24, 2021

Welcome to the Phase 2 set of challenges. This new set of challenges are more challenging with lots of planned goodies in store to share with you guys. The first challenge is to create a new enemy movement.

Enable the enemies to move in a new way, either from side to side, circling, or coming into the play-field at a new angle.

I’ve given this challenge a bit of thought and decided to create some randomness that would keep the player on edge. When an enemy is spawned, it generates a Random.Range number between -1 and 2returning a value of -1, 0, or 1. If the value is -1 then the enemy would move to the left, if the value is 0 the enemy would move downwards and if the value is 1 then the enemy would move to the right. I also set that if the enemies move to the edge of the screen, they’d turn in the opposite direction.

Random Movement

In the Start function, I added a new int and called it randomMovement and set the Random.Range between -1 and 2. Once I have a value I run one of 3 if/else statements to determine the movement. I’ve also created a new float value called _sideSpeed to determine how fast the enemy will move in a sideway direction. Here I also used Random.Range values between 0 and 3 would cause some enemies to move in a sideways direction faster than others.

Enemy Screen Clamping

At this point, the enemies are moving sideways as expected but at a point, they leave the screen which we don’t want. We need to check when they reach the side of the screen and then make them move in the other direction.

The enemy has a function called EnemyMovement() which we can add our location checks and flip the direction the enemy is moving in. All that we need to do is check if the enemy reached the positions of -9 and 9 on the screens, and reverse the speed. Remember I created that float called _sideSpeed? well, when we reach the sides all we need to do is _sideSpeed = -_sideSpeed; and that would reverse the sideways movement.

Conclusion

With about 30 lines of code, we have enemies with random movement behaviour which adds a nice touch to the enemies from just moving in a predictive downwards direction.

Spoiler Warning: You may see things in the gif that I haven’t covered yet. My course progress is slightly ahead of my articles. Also, I’ve reskinned my game in preparation for future challenges and the big finale that’s coming up.

--

--

Dominique Dos Santos
Nerd For Tech

Self-taught Unity and C# Developer with a passion for games and the stories they tell.