Elliptical Enemy Movement

Blake Zoeckler
4 min readJun 2, 2021

--

How can we make enemies move like this?

Today we’ll be using the EnemyBehavior component system we created last time to add a much more exciting and innovative form of movement. We want some enemies to appear from the bottom edge of the screen, move upward, and then travel in an ellipse until they are destroyed.

EnemyBehavior.FireLaserRoutine

Doing this will require a new kind of EnemyBehavior class, with variables such as whether or not the enemy has reached the elliptical part, the current angle from the center of the ellipse, the shape of the ellipse, and so on. We can inherit from the BasicEnemyBehavior class because we want to use the same FireLaserRoutine coroutine that it has.

Next, we should override the Start method. We call the same basic behavior setup that EnemyBehavior has, start the laser firing coroutine, and set up the shape of the ellipse based on variables that are set in the inspector. Then we move this enemy below the edge of the screen, since we want it to move straight upward until it reaches the vertex of the ellipse.

Then the Act method will check if the enemy has reached the ellipse. If it hasn’t, it will move the enemy upward until its above the center of the ellipse.

After that point, it will use the SetPositionByAngle to transition to moving around an ellipse. We can use the trigonometric functions sin and cos to find the exact coordinates of where the enemy should be placed.

The best part about using inheritance is that we don’t even need to change the Enemy class at all to use EllipticalBehavior! Since EllipticalBehavior inherits from EnemyBehavior, that means our Enemy code can recognize it as a type of EnemyBehavior, and we can just attach it to a new enemy prefab.

Enemy.Update is so smart!

Enemy.Update will call it’s Act method all the same. With the power of polymorphism, the code will automatically figure out at runtime whether we are using BasicEnemyBehavior or EllipticalBehavior and use the Act method from the right one.

Now we set the spawn manager to use this new enemy prefab, and we can this new movement pattern in game!

There’s one last improvement we can make here. We would like to still have some enemies to move the old way, so we can have some enemies move forward while others move elliptically. To do this we can change SpawnManager’s enemy variable to be an array of GameObject instead of just a single one. Then we can just randomly pick one of the enemy prefab types that we put into the array.

Inside the SpawnManager coroutine that creates enemies

With the spawn manager changing enemy movement types randomly, now we get a nice mixture of different enemy movement, making the game much more lively!

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet