distance

 

distance is a turtle and patch primitive that reports the shortest distance between the current agent and another provided agent. For example, the following code would make the turtles who are close enough to the center patch (0,0) move one step forward, but if their distance to the center patch (0,0) is 5 units or more, they would not move.

ask turtles [
    if distance (patch 0 0) < 5 [ forward 1 ]
]

Things to keep in mind when using distance:

In the model example below, we use distance to implement a rudimentary path finding behavior for a lumberjack. The lumberjack has a "target" tree that they will try to move towards and cut down. Once they cut down that tree, they will set their eyes to the closest tree. We use distance to get the distance between the lumberjack and all of the trees so that we can figure out which tree is closest. In the case of ties, we choose one of the closest trees randomly.

 

Try it Yourself

 
 
 
 
 
 
 

What's next?

Once you mastered the distance primitive, don't stop there. Check out the resources below to improve your NetLogo skills.

 
Published NetLogo models that use the distance primitive:
 
 
Similar primitives:
facexy

Changes a turtle's heading towards a specific point (x, y) in the world.

Read more
min-pxcor

Reports the smallest x-coordinate of the patches in a model.

Read more
patch-ahead

Reports the single patch that is the given distance “ahead” of this turtle

Read more
setxy

Moves a turtle to the exact location defined by the provided x and y coordinates.

Read more
 
Learn another primitive: