Abhishek Bhatia
Abhishek Bhatia

Reputation: 9796

Unable to calculate distance between patches when inside ask turtles

Please help with the following code:

     ask turtles[
       ......
       let new-patches no-patches
       ask patch-here [ set new-patches neighbors]
       let new-patch min-one-of new-patches [distance goal-patch] 
       face new-patch
       .....
]

Aim: I want the above code to make the turtle to face towards the patch which is nearest to a given patch ("goal-patch").

Obvious approach not followed: The reason I don't directly use facexy is that there are obstacles in between so the turtles get struck.

Error:

 let new-patch min-one-of new-patches [distance goal-patch] 

this code can't be run by a patch error while turtle 101 running DISTANCE

Upvotes: 2

Views: 667

Answers (1)

TurtleZero
TurtleZero

Reputation: 1064

It looks like goal-patch is probably a turtles-own'd variable.

In that case, the expression "distance goal-patch" is a turtles-only expression. It only has meaning to a turtle. So, a patch can't run it. In other words, the patch does not have access to any variables called "goal-patch".

You need to provide the value of goal-patch in a way that a patch can use. You can either use [ goal-patch] of myself or you can save the value of goal-patch in a temp variable.

However, this ignores the real problem with this code, is that you are trying to choose among the neighbor patches that are nearest the goal patch, and your code is very complicated for that.

See, turtles can use "neighbors" directly. So, if you want to find the neighbor patch nearest the patch contained in the turtles-own'd variable goal-patch (using distance), it is:

set nearest min-one-of neighbors [ distance ( [ goal-patch ] of myself ) ]
;; parenthesis added for emphasis
;; --distance can't be inside the brackets with goal-patch

In this context, myself refers to the turtle running this line of code. "Myself" is a tricky reporter, and understanding it is important to writing inter-agent interactions correctly.

Hope this helps.

Upvotes: 2

Related Questions