Search code examples
netlogo

moving turtles forward to a target in one tick


I'm working on a hospital model, and I want nurses to choose one of the patients as their target and move forward until they reach their patients in one tick. I use while in my code, but it only moves one patch forward in one tick. here is my code:

to nurse-visit
ask nurses 
[ let target one-of patients
if distance target = 0
[face target]
;;move towards target. once the distance is less than 1
ifelse distance target < 1
[move-to target]
[while [any? patients in-radius 1]
[ fd 1 ]]

Is there anyone here that can help me?


Solution

  • It might be helpful to break down the lines into pseudocode to figure out it's not working. At the moment, your code is saying:

    if distance target = 0
    [face target]
    

    If the distance to the target is 0, face the target. In NetLogo, facing the target once the distance to the target is 0 is meaningless since they share a location.

    ifelse distance target < 1
    [move-to target]
    

    If the target is less than 1 patch away, move to it. That's great- we can reuse this bit later, we just need to change the order a little.

    [while [any? patients in-radius 1]
    [ fd 1 ]]
    

    While any patients are nearby, move forward. Here, we probably want to refer to the target instead of the general patients.

    So overall, it seems like the logic and order of operations is not quite right. What we really want to do is for each nurse to:

    • Pick a target patient
    • Determine the distance to that patient
    • Until the distance to the target is exactly 0, do one of two things:
      • If the distance to the target > 1, face the target and move forward 1
      • If the distance to the target is < 1, move right to the target

    Translating that to code, you could do something like:

    breed [ nurses nurse ]
    breed [ patients patient ]
    
    to setup
      ca
      ask n-of 5 patches [ sprout-patients 1 ]
      create-nurses 1 
      reset-ticks
    end
    
    to nurse-visit
      ask nurses [
        ; Pick a patient
        let target one-of patients
        
        ; Until my distance to my target is 0, do the following:
        while [ distance target > 0 ] [
          
          ifelse distance target > 1 [
            ; If the distance to my target is greater than 1, face
            ; the target and move forward 1
            face target
            fd 1
            wait 0.1
        ] [ 
            ; Otherwise, move *exactly* to the patient
            move-to target
          ]
        ]
      ]
    

    Note that I've put a wait timer in there so you can see the nurse moving regardless of your display speed.