OverlapSphere

var OnSightTowers = Collider[];
    function Update(){
       LookingForTarget();
    }
    function LookingForTarget(){
       onSightTowers =Physics.OverlapSphere(transform.position,sightDistance,TowerMask);
       if(OnSightTowers.length!=0){
          myTarget = onSightTowers[onSightTowers.length -1].transform;
         }
    }

Hi all,

I have a little bit problem here. Above is my code. I’;m planning to use OverlapSphere as my AI sight area.

The problem is the content of onSightTowers Array keep changing. Whenever new target get closer, The array order is changing. Some time an object is inside array[0], but the next moment it become arrya[1],So I have no idea how to find the closest target. The closest target is the first target that collide with the OverlapSphere.

Sorry for my bad English. Do I explain it clear enough?

You need to find the closest of the results yourself:

function ClosestToPoint( point : Vector3, list : Transform[] ) : int {
  var distance : float = list[0];
  var closest : int = 0;
  for ( var index : int = 1; index < list.length; index++ ) {
    if ( (list[index].position - point).sqrMagnitude < distance ) {
      closest = index;
      distance = (list[index].position-point).sqrMagnitude;
    }
  }
  return closest;
}

What’s “point” here?

also list[0] is a transform. But you set a var distance:float = list[0]

I don’t really get it. Can you explain more? :slight_smile: thanks

Whoops, typing waaay too fast. xD

point would be the center point. That function returns the thing in list which is closest to that point.

So if you pass the resulsts of a physicsOverlapSphere, and the center of the sphere, you’d get the closest object to the center point. :smile:

That line should be

  var distance : float = (list[0].position - point).sqrMagnitude;

Essentially we’re defaulting distance to be the distance to the closest item, so there’s fewer for-iterations and ever so slightly better performance.

This works quite well:

Transform FindNearestTarget(float radius){ 
	    float minDist = Mathf.Infinity;
	    Transform nearest = null;
	    Collider[] cols = Physics.OverlapSphere(transform.position, radius);
	    foreach (Collider hit in cols) {

	            float dist = Vector3.Distance(transform.position, hit.transform.position);
	            if (dist < minDist){
	                minDist = dist;
	                nearest = hit.transform;
	        }
	    }
	    return nearest;
	}