Journal 41 — Aggressive Enemies in Unity Space Shooter

Chris Nielsen
2 min readJun 12, 2021

In this challenge, we have to update the behavior of some enemies, so that if they get close to the player, they will try to ram the player. I also wanted to include behavior such that if the player gets far enough away, the enemy will return to its normal movement. For this update, I will only modify the base movement, and leave the custom movement of two other enemies alone (one that follows a waypoint system, and one that has no laser fire, but attacks the enemy by swarming it).

In the Enemy base class Update method, we can first add a condition to check the distance from the enemy to the player.

Unity C# script for Enemy base class, check distance in Update method

Next, I modified the movement function to make it a switch statement.

Unity C# script for Enemy base class, update Calculate Movement function

We check the distance from the enemy to the player, and set the new enemy position towards the player.

We also include a RotateTowards function so that the enemy always faces the player.

Unity C# script for Enemy base class, add rotate function

In order to return to normal movement, we need to return the enemy’s current rotation back to its original rotation smoothly using Quaternion.Slerp. So in the Start method when the enemy is first instantiated, we save it’s original rotation.

And finally, you can see this in action in Playmode.

Unity Playmode with aggressive enemies

Thank you for stopping by!

--

--

Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.