- Home /
,How to find closest enemy in line of sight, among enemies behind the wall and in line of sight
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[i];
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);
Answer by VoidPhoenix96 · Feb 17, 2021 at 01:25 AM
Use Physics.Raycast()
In Unity, when creating lines of sight, that is what you should use most of the time.
Answer by Buzzlai · Feb 17, 2021 at 07:33 AM
Thx for the answer. Im using phisics2D.raycast. i suposed was the same. I think the problem is ithe way i find the closest.
Your answer
Follow this Question
Related Questions
My Player only gets hurt on one side 0 Answers
Enemy walking off platform in 2D mode 1 Answer
Is this the most efficient way to attack the closest enemy? 0 Answers
2d raycast enemy detection problem. 0 Answers
Raycast2D enemy and player problem 0 Answers