Aggressive Enemies

Christian Carter
1 min readAug 25, 2021

--

This tutorial will cover how to make enemies more aggressive and move towards the player if the player gets too close. This will all be handled in the Enemy script. First add a variable that will be used for how close the player needs to be for the enemy to move towards it.

[SerializeField] private float _aggroRange = 4f;

The Enemy script already has a reference to the Player. This will be used to get the position of the player. Then if the distance to the player is less than our limit the enemy will move towards the player. This will use the Vector3.Distance function to calculate the distance between the player and the enemy. This will all be done at the beginning of the CalculateMovement function. Put the rest of the movement calculations inside an else statement after this if statement.

if (Vector3.Distance(gameObject.transform.position,
_player.transform.position) <= _aggroRange)
{
Vector3 directionVector = _player.transform.position -
ransform.position;
directionVector.Normalize();
transform.Translate(directionVector * _speed * Time.deltaTime);
}

You can adjust the distance the enemy will move towards the player by changing the aggroRange variable.

-Chris

--

--

No responses yet