Journal 41 — Aggressive Enemies in Unity Space Shooter
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.
Next, I modified the movement function to make it a switch statement.
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.
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.
Thank you for stopping by!