Message Boards Message Boards

[?] Control animations with FinishDynamic[]?

Posted 7 years ago

Here is a simple example of visualizing a 2d random walk. It is constructed to illustrate my question about FinishDynamic[]

I am also attempting set up controls for an interactive animation. I'd like a dynamic to update and use "stop" and "go" buttons.

Here are two functions that are used in the animation of a simple random walk:

Add a random step to a list of random steps:

updateRandomWalk[list_] := 
 Append[list, Last[list] + RandomReal[{-0.5, 0.5}, {2}]]

Visualize the sequence of steps:

displayWalker[list_] := {Line[list], Disk[Last[list]]}

For example:

walkers = ConstantArray[{{0, 0}}, 100];
Do[walkers = updateRandomWalk /@ walkers;, {2000}];
Graphics[displayWalker /@ walkers, PlotRange -> 50 {{-1, 1}, {-1, 1}}]

Attempt to create an animation with a stop and go button. Notice that the FinishDynamic is being ignored--and that the animation stops even if the stop button is not activated.

DynamicModule[{walkers = ConstantArray[{{0, 0}}, 50], animate = False},
 Column[
  {
   Row[{
     Button["Go", 
      animate = True;
      While[animate, walkers = updateRandomWalk /@ walkers; 
       FinishDynamic[];]
      ],
     Button["Stop", 
      animate = False,
      Method -> "Preemptive"
      ]
     }
    ],
   Dynamic[
    Graphics[displayWalker /@ walkers, 
     PlotRange -> 50 {{-1, 1}, {-1, 1}}]
    ]
   }
  ]
 ]

Thanks. Mathematica 11.1 on MacOs 10.12.4 (Sierra).

POSTED BY: W. Craig Carter

Craig,

you need to add a Method-> "Queued" to the go button

DynamicModule[{walkers = ConstantArray[{{0, 0}}, 50], 
  animate = False}, Column[{Row[{Button["Go", animate = True;
      While[animate, walkers = updateRandomWalk /@ walkers;
       FinishDynamic[];], Method -> "Queued"], 
     Button["Stop", animate = False, Method -> "Preemptive"]}], 
   Dynamic[Graphics[displayWalker /@ walkers, 
     PlotRange -> 50 {{-1, 1}, {-1, 1}}]]}]]
POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract