Amy
Amy

Reputation: 91

Minimum distance between turtles

I am trying to write code that calculates the distance between turtles. They need to move away if too close to each other and move closer if too far apart.

They can be no closer than 1/2 of a patch and no further than 1 patch. If they aren't between 1/2 and 1 patch distance from each other, then they need to move until they are within this range.

Would I have to link them to do this or can I do this unlinked?

Upvotes: 2

Views: 2337

Answers (1)

JenB
JenB

Reputation: 17678

Since you are doing this in setup, then what you could do is have NetLogo create the turtles gradually and make sure each is a suitable distance. There is a logical issue, that the first turtle should not be tested for distance since there's no other turtles, and you are assuming that there are few enough turtles that they can fit in the world with those distance restrictions.

Nevertheless, here is some code that will do it (for 9 turtles). It does run the risk of an infinite loop though if you try and create too many turtles. It is also incredibly inefficient as the number of turtles increases because a turtle is randomly placed until it finds a suitable location and that may take several attempts.

to setup
  clear-all
   create-turtles 1
   repeat 8
   [ let min-x min [xcor] of turtles - 1
     let max-x max [xcor] of turtles + 1
     let min-y min [ycor] of turtles - 1
     let max-y max [ycor] of turtles + 1
     create-turtles 1
     [ loop
       [ setxy random-float (max-x - min-x) + min-x random-float (max-y - min-y) + min-y
         let close-turtles other turtles-on (patch-set patch-here neighbors)
         let how-close distance min-one-of close-turtles [distance myself]
         if how-close > 0.5 and how-close < 1 [stop]
       ]
     ]
   ]
end

Upvotes: 3

Related Questions