- Home /
finding closest n objects
I have this code so far, which works fine:
public GameObject FindClosestWaypoints(){
nameOfWaypoint = MouseClick.clickedWaypoint;
Debug.Log(nameOfWaypoint);
positionOfGetWaypoint = GameObject.Find (nameOfWaypoint).GetComponent<Transform>();
waypointLocations = GameObject.FindGameObjectsWithTag("Waypoint");
float distance = Mathf.Infinity;
foreach (GameObject x in waypointLocations){
Vector3 diff = x.transform.position - positionOfGetWaypoint.transform.position;
if(x.transform.position != positionOfGetWaypoint.transform.position)
{
float curDistance = diff.sqrMagnitude;
if (curDistance < distance){
closestWaypoint = x;
distance = curDistance;
}
}
}
Debug.Log ("The closest waypoint was found and it is located at " + closestWaypoint.transform.position);
return closestWaypoint;
}
However, the problem with the code is that I only got it to return the closest waypoint gameobject. If I want it to return the closest 2/3/4/5 game objects, how would I do so?
Upon finding a close point you could add it to a list/array, then for each subsequent close point you could deter$$anonymous$$e if you are under your required point count, in which case add it to the list, or if you have enough points, compare the new points distance to all of the close points. if it is closer then you can replace the old point with the closer one. Repeat until you run out of points.
Hopefully that was some what clear to you...
You can also use a OverlapSphere (or similar) raycast in order to only get waypoint objects within your desired range. It might reduce the number of waypoints you have to sift through.
^This would rquie the waypoint objects to have trigger colldiers, though, and the player object having a way to register those.
BTW, here is some sample code that sorts GameObject based of their distance.
objectList.Sort(delegate(GameObject c1, GameObject c2){
return Vector3.Distance(this.transform.position, c1.transform.position).CompareTo
((Vector3.Distance(this.transform.position, c2.transform.position)));
});
RougelikeShadow: that's a Selection Sort (that's the official name for a standard sorting method.)
The way to find "first N" is to sort the entire list, then take the first N of them. Obviously, you pre-compute and save distances, ins$$anonymous$$d of re-computing for each compare.
A Selection Sort naturally works by finding the closest, next closest ... so it's easy to stop it after you're gotten just the first N.
Cherno's solution is using a faster sort (N log(N).) But sorts the entire list.So might be faster or slower depending on sizes (first 5 out of 10, or out of 1000?) But, looks like it computes distance over and over for each compare, so won't run as fast as it could.
Thanks that's actually really useful to have an official name for that.