Finding the Closest Object

Finding the closest object can be slightly more complicated than simply getting the neighbors, because it's possible that the closest object is not within an object's neighborhood. However, assuming that some number of neighbors are found for your agent, the following code should help:

+ to find-closest-neighbor:
        closestNeighbor (object).
        distance, minDistance (float).

        # start with an arbitrarily high distance

        minDistance = 1000000.

        foreach i in (self get-neighbors): {
                distance = | (self get-location) - (i get-location) |.

                if distance < minDistance: {
                        minDistance = distance.
                        closestNeighbor = i.
                }
        }

        return closestNeighbor.

If there are no neighbors within the local neighborhood then it is sometimes necessary to do a search of all agents in the simulation. To do this, the code above can be modified by using an all statement (the section called “Finding All Objects of a Given Type”) in place of the "self get-neighbors" expression:

        foreach i in (all "Reals") {
                # code to select the closest neighbor
        }