How to find the nearest agent in a particular direction in NetLogo?

Viewed 33

In the basic traffic model included in the models library, adding the following line:

ask turtles with [color = red]
[set car-ahead min-one-of other turtles in-cone 50 0 [distance myself]]

will set the car-ahead to be a car that may be behind the red car. How could I force the minimum distance to be in the direction of travel - to find the nearest car in front?

2 Answers

There are several options here.

The first option I had was to reduce how far ahead the turtle looks. Only the cars that fall at most half of the world length ahead of the car are considered to be ahead. Oh course this might mean there is not always a car that can be considered the closest car in front, so it might not be sufficient depending on what exactly you need.

  ask turtles with [color = red] [
    let half-size (max-pxcor - min-pxcor) / 2
    set car-in-front min-one-of other turtles in-cone half-size 0 [distance myself]
    ask car-in-front [set color yellow]
  ]

The next version instead insures that there is always a car infront of the focal car. I removed the in-cone for this specific example because in the basic traffic model, every single other turtle is in the cone that you specified. First of, I use (xcor - [xcor] of myself) checks for each other turtle how far in front of the focal turtle thay are. This gives you some problems with world wrapping. That is why I added the second part (xcor - [xcor] of myself) mod (max-pxcor - min-pxcor). The modulus of the total world length ensures that if the result of (xcor - [xcor] of myself) is a negative number, it is substracted from the world length with a positive number as result.

  ask turtles with [color = red] [
    set car-in-front min-one-of other turtles [(xcor - [xcor] of myself) mod (max-pxcor - min-pxcor) ]
    ask car-in-front [set color yellow]
  ]

That's what the zero in "in-cone 50 0" accomplishes. See the dictionary.

in-cone distance angle

This reporter lets you give a turtle a "cone of vision" in front of itself. The cone is defined by the two inputs, the vision distance (radius) and the viewing angle. The viewing angle may range from 0 to 360 and is centered around the turtle's current heading.

Related