I’m trying to make an object, in this case an enemy, continuously chase after the player while avoiding obstacles.
⠀
I’m casting two rays to detect any obstacles and then, if there are obstacles, change the velocity so it avoids them. However, the enemy struggles when the player circles around an obstacle. It continues to follow the player when moving out of the way so it ends up running into the obstacle, gets stuck and sometimes moves in the opposite direction.
⠀
//private int range = 3;
//private float speed = 1.0f;
//LayerMask obstacles = LayerMask.GetMask("Obstacles");
public void MoveToTarget(Transform _target)
{
Vector2 _dir = _target.position - transform.position;
RaycastHit2D _hit = Physics2D.Raycast(transform.position - new Vector3(0.5f, 0.5f, 0.5f), _dir, range, obstacles);
RaycastHit2D _hitTwo = Physics2D.Raycast(transform.position + new Vector3(0.5f, 0.5f, 0.5f), _dir, range, obstacles);
if (_hit.collider != null || _hitTwo.collider != null)
{
dir = Vector2.Perpendicular(_hit.normal);
}
rb.velocity = _dir.normalized * speed;
}
⠀
It will continue to follow the player given enough time but it stops for moment before resuming to chase. I’ve tried playing around with the range of the raycast, speed of the enemy and size of the obstacle but those don’t make any difference.