New Enemy Type: Dodger
How to create projectile avoid behavior
In this article we create enemy behavior to dodge incoming player laser.
We will be using Raycast just like when we used it to make the enemy shoot at a powerup.
BoxCast
We will need to use a different RayCast in this case. The standard Raycast only checks for colliders in a single line. Our enemy needs to dodge not only lasers that are coming at it right in the center. To do this we use BoxCast.
Enemy Dodge Behavior Script
The code uses BoxCast to check in front of the enemy and if the first thing the cast hits has the tag laser it teleports and dodges to a random side. To prevent the enemy from endlessly dodging all player laser we put in a bit of a cooldown on the dodge.
[SerializeField] private float _dodgeRate = 1.5f;
private float _dodgeRange = 1.5f;
private float _nextDodge = 0f;
private Vector2 _boxSize = new Vector2(2.5f,0.01f);
private float _maxDistance = 20f;
private float _angle = 0f;
private Vector3 _offset = new Vector3(0, -2f, 0);
private Collider2D _collider;
private void Start()
{
_collider = GetComponent<PolygonCollider2D>();
if (_collider == null)
{
Debug.LogError("EnemyMoveDodge.collider is NULL");
}
}
void Update()
{
if (_collider)
{
RaycastHit2D hit = Physics2D.BoxCast(transform.position + _offset, _boxSize, _angle, Vector2.down, _maxDistance);
if (hit.transform.tag == "Laser" && Time.time > _nextDodge)
{
_nextDodge = Time.time + _dodgeRate;
if (Random.value > 0.5)
{
_dodgeRange *= -1f;
}
transform.Translate(Vector3.left * _dodgeRange);
}
}
}