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.

Declared a Transform variable
Getting a Handle on the Player’s Transform

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.

Getting the Look Direction

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.

Moving the Up towards the Player

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.

Transform Up

Now we have the enemy rotating towards the player, we want it to move towards the enemy with that look direction.

Moving the Enemy towards the Player using the 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.

Final Code Example

Hopefully this was helpful!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store