Hello! im new here. hope to find some light. im trying to find the closest enemy in line of sight.
Is a top down shooter, where there could be enemies behind a wall and in line of sight. i want to face enemies in line of sight when they are, and when there are no one in line of sight, just select the closest.
This is my code. now, i only select the closest. Thanks in advance.
_allEnemy = _dungMan._enemyList;
float distanceToClosestEnemy = Mathf.Infinity;
_enemy = null;
int count = _allEnemy.Count;
for (int i = 0; i < count; i++)
{
GameObject currentEnemy = _allEnemy*;*
float distanceToEnemy = (currentEnemy.transform.position - transform.position).sqrMagnitude;
if (distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
_enemy = currentEnemy;
RaycastHit2D hit;
if (hit = Physics2D.Raycast(transform.position, currentEnemy.transform.position, Mathf.Infinity, _obstacleLayer))
{
if (hit.collider.CompareTag(“Enemy”))
{
distanceToClosestEnemy = distanceToEnemy;
_enemy = currentEnemy;
}
}
}
}
Debug.DrawLine(transform.position, _enemy.transform.position);