Pause Line Execution Until Condition Happens in P5

I am making an abacus simulator in p5 (sketch file) that does all the moves step by step. To animate the movement, I have variable x incrementally increase/decrease in a show function I created (lines 166 and 172), which is getting called in draw() over and over again. It knows what to do based on the state (bead on left or right side).

I am currently writing a function add(a, b) that adds two numbers. It works correctly, but it only animates the final answer instead of animating it step by step (lines containing //animate should be what animates). When I change the row variable (two-dimensional array) in a for loop, I would like to have it fully animate (I think by calling the show function within the loop) before iterating through the next row element. The lines with //animate in it are what I want to animate. I’ve tried doing a while loop to stall it, but it doesn’t work and show() needs to get called over and over again before proceeding.

I’ve even tried running a for loop (with distance / speed) which should be the number of times (11,100) show() would need to get called to fully animate to the other side. None of these things are working! Any ideas how I can make line execution not continue until it finishes animating (starting at line 93 in add())? Try it out first in the console with the add function. I am going to be doing some refactoring later.

draw() is your animation loop – it updates the screen every time it ends. You need to work within that constraint. You can’t update the screen multiple times within a single draw loop – instead you need to build something outside / around draw, even if it is just state.

Here is one approach that will work.

  1. on input, add an action to a queue of actions
  2. if all beads are at their targets, start the next queued action
  3. on action (with all beads at rest), set new location targets for selected beads

Separately from this, in draw, implement all animation like this:

  1. If a bead is not at its target, move it towards its target.

Now the speed of individual bead motion will also control how fast actions get processed out of the queue. But the queue system doesn’t know anything about animation – it is just a list of operations – and the action targeting system doesn’t know about the queue – it just takes a static list of beads and described their new positions – and the animation system doesn’t know anything about actions – it just moves any beads that aren’t “there yet” closer to wherever they want to go.