Question

Using mouse-down? for mouse actions in NetLogo often results in the action happening too many times. For example, if you want to let users click to create new turtles, you could hook a forever button up to a procedure like:

to add-turtle
  if mouse-down? [
    crt 1 [ setxy mouse-xcor mouse-ycor ]
  ]
end

The problem is that this usually results in many turtles being created per click. I'd like to do something like:

to add-turtle
  if mouse-clicked? [
    crt 1 [ setxy mouse-xcor mouse-ycor ]
  ]
end

Where mouse-clicked? is true right as the person clicks (right after they left up the mouse button).

Was it helpful?

Solution

Unfortunately, you do have to keep track of it yourself, but the good news is that its not hard.

The key is to create a global called mouse-was-down? that is set to true if mouse-down? was true in the last time your mouse-oriented procedure was called. Then mouse-clicked? can be defined as follows:

to-report mouse-clicked?
  report (mouse-was-down? = true and not mouse-down?)
end

It seems to work well in conjunction with a central mouse-management procedure that calls the other click-based procedures. For example:

globals [ mouse-was-down? ]

to-report mouse-clicked?
  report (mouse-was-down? = true and not mouse-down?)
end

to mouse-manager
  let mouse-is-down? mouse-down?
  if mouse-clicked? [
    add-turtle
    ; Other procedures that should be run on mouse-click
  ]
  set mouse-was-down? mouse-is-down?
end

to add-turtle
  crt 1 [ setxy mouse-xcor mouse-ycor ]
end

Using the mouse-is-down? local variable keeps the behavior more consistent if the mouse button is released before mouse-manager finishes.

OTHER TIPS

Hello probably this is a bit late for your purpose, but in case anyone has the same problem, this is how I solved this in my models for now.

to add-turtle
  if mouse-down? [
    crt 1 [ setxy mouse-xcor mouse-ycor ]
    stop
  ]
end

The workaround here is to add a "stop" command to kill the "create-new-turtle" forever button. The only tradeoff is that you will have to press again to create another new turtle.

Bryan Head's answer didn't work for me, it still created multiple turtles in one click.

Alternative:

A (non-forever) button which does crt 1 [ setxy mouse-xcor mouse-ycor ]
with action key A.

Now all you need to do to add a turtle is press or hold A with your left hand while mousing with your right hand.

Here is an alternative to Bryan's code, in case you want to perform an action as soon as the mouse button is clicked (instead of waiting until it's released):

globals [ mouse-clicked? ]

to mouse-manager
  ifelse mouse-down? [
    if not mouse-clicked? [
      set mouse-clicked? true
      crt 1 [ setxy mouse-xcor mouse-ycor ]
    ]
  ] [
    set mouse-clicked? false
  ]
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top