# How to make object move to next closest object ?

I would like to enhance this couple of methods. Currently they move object to first closest object and it stops there. I need it to continue.

``````Transform[] wayPointList;
int currentWayPoint;
Transform targetWayPoint;

...

void MoveToClosest() {
targetWayPoint = GetClosestWayObject(wayPointList);
currentWayPoint = Array.IndexOf(wayPointList, targetWayPoint);
transform.forward = Vector3.RotateTowards(transform.forward, targetWayPoint.position - transform.position, rotationSpeed*Time.deltaTime, 0.0f);
transform.position = Vector3.MoveTowards(transform.position, targetWayPoint.position,  speed*Time.deltaTime);

}

....

Transform GetClosestWayObject(Transform[] objects) {
Transform tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;

foreach (Transform t in objects)
{
float dist = Vector3.Distance(t.position, currentPos);
if (dist < minDist)
{
tMin = t;
minDist = dist;
}
}
return tMin;
}
``````

Make â€śGetClosestWayObjectâ€ť check that it doesnâ€™t return the current waypoint, then call â€śMoveToClosestâ€ť again.

Thanks, but I thatâ€™s too general. Do you have more concrete (detailed) ideas ?

He means that the waypoint youâ€™re currently standing on is the closest waypoint. So as long as youâ€™re standing on it, that will always be your â€śclosest waypointâ€ť and you wonâ€™t be able to continue from there.

So you need to exclude the current waypoint to find the next closest waypoint.

One way to do that would be to check if the distance is too small, then ignore that waypoint.

1 Like