New Enemy Type: Rusher
Get too close and this enemy will ram the player
In this article we create a new enemy type: rusher. This enemy will detect if the player gets close and will start chasing the player down. The player can use the thrusters/sprint or the wrap around mechanic to lose the rusher.
Rusher type Enemy Behaviour Pseudocode
If distance to player is less then minimum distance
then start rushing towards the player
and change rotation based on the move direction
else move down straight
and change rotation based on the move direction
Actual Code
Created necessary variables and a handle to the player:
private GameObject _player;
[SerializeField] private float _speed = 2f;
[SerializeField] private float _minDistance = 4f;
private float _rushSpeed = 4f;
private Vector3 _targetPos;
private Vector2 _direction;
// Start is called before the first frame update
void Start()
{
_player = GameObject.FindGameObjectWithTag("Player");
if (_player == null)
{
Debug.LogError("EnemyAttackRush.player is NULL");
}
}
We used the Vector3.Distance function to detect if the player got close to the rusher.
To move towards our target (player) we used Vector3.MoveTowards
void Update()
{
if (Vector3.Distance(transform.position, _player.transform.position) <= _minDistance)
{
_targetPos = _player.transform.position;
transform.position = Vector3.MoveTowards(transform.position, _targetPos, _rushSpeed * Time.deltaTime);
//change direction to movement direction
_direction = (transform.position - _targetPos).normalized;
float angle = Mathf.Atan2(_direction.y, _direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle + 270f, Vector3.forward);
}
else
{
transform.Translate(Vector3.down * _speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(0,0,0);
}
}
To change the rotation when we are going straight down we just used a fixed angle.