Finding Neighboring Objects
<< previous | Chapter 7. Interactions Between Agents | next >>

## Finding Neighboring Objects

The slow way to find neighboring objects is to look at every object in the simulation and determine whether they are close enough to be considered neighbors. To repeat this process for N objects that we want to keep track of, N*N checks are required for each iteration. This quickly becomes an inefficient bottleneck.

breve offers a solution to this problem in which the time required to find neighbors grows roughly linearly with the number of the objects in the simulation. The feature is referred to as neighbor checking. Neighbor checking is done in three steps:

1. Set each agent's "neighborhood size".

2. Ask the engine to update the neighbors at each iteration.

3. Retrieve each agents list of neighbors at each timestep.

The neighborhood size specifies the distance that each agent will look in order to find any neighbors. The distance between two objects is, in this case, defined as the distance between the center-points of the objects. Setting the neighborhood size is typically done during object initialization, but it may be changed at any time during the simulation. Neighborhood size is set using the method set-neighborhood-size in Real.tz. Real is the parent class of both Stationary and Mobile objects, so the method can be used with these classes as well.

The second step, updating the neighbors, is done with a call to the method update-neighbors in the iterate method of your simulation's controller object.

The final step of retrieving the neighbors is done using the get-neighbors method of Real.tz. This method returns the neighbors as a `list`. For example, the following iterate method would print out a list of the agent's neighbors at each time step, assuming that the neighborhood size has been set and that the neighbors are being updated:

    + to iterate:
            neighbors (list).
            item (object).

            neighbors = (self get-neighbors).

            foreach item in neighbors: print "$item is in my neighborhood.".

<< previous | Up | next >>
Triggering Events When Agents Collide | Table of Contents | Finding the Closest Object