Aggressive Enemies
In this article I will go over how to create aggressive enemies that will follow you.
The first thing we need to get is the player’s transform, so we know where the position of the player.
There is a simple line that we can place in the Update that allows us to move a game object towards another.
In this line, we are setting the transform position to a Vector3.MoveTowards, which requires the current Vector3 position, the target Vector3, and a speed.
This results in the Enemy sharply following the player, but we want to give some wiggle room. If the player dodges the enemy it should take some time for the enemy to circle back around. Also, the enemy is not rotating towards the player so it is always facing the player.
In the Update, we need to get the look direction of the enemy and we do this by subtracting the position of the enemy from the player position.
We are going to set the transform.up to a Vector3.MoveTowards. This will move the transform.up towards that player. To do this we place in the transform.up, the look direction as the target and a rotation speed * Time.deltaTime.
Now we have the enemy rotating towards the player, we want it to move towards the enemy with that look direction.
Lets set the transform position to the Vector3.MoveTowards passing in the current position of the enemy, the target will be the current position plus the look direction (remember it is facing the player), and we will pass a speed.
In the script, I added a SerializedField attribute to both the enemy speed and rotation. The slower the rotation of the enemy, the more time it will take the enemy to recover after a player dodge.
Hopefully this was helpful!