So I am trying to write an ai behavior for my game where the npc characters will rotate to look at the closest target (a piece of food) to them. I have written code I thought would work, but when applied they just rapidly switch between all targets in the raycast, instead of focusing on the closest one.
Vector3 GetTargetLocation()
{
RaycastHit2D[] hit = Physics2D.CircleCastAll(transform.position, SenseDepth, Vector2.up, SenseDepth, mask) ;
for (int i = 0;i < hit.Length; i++)
{
float currentTarget;
currentTarget = 10000;
if (hit[i].distance< currentTarget)
{
currentTarget = hit[i].distance;
senseTarget = true;
Vector3 target = hit[i].point;
Debug.DrawLine(transform.position, target);
return target;
}
}
senseTarget = false;
return Vector3.zero;
}
This is the code I have to get the targets location to then rotate towards. I might’ve made some obvious mistake, slightly new at this.