Animated plot

I have two objects that I want to plot in an interactive graph.

  • bar: is controlled via PlutoUI.Slider which can change the x position
  • square: shall move around irrespective of the bar movement. For the below MVP the square is just moving randomly.

Unfortunately, the square only moves when I move the slider to move the bar. This makes sense to me given this is triggering the update of the plot.

Two questions

  1. is there a way to trigger the square movement independently and in a way that I can “start” it once and it moves until I trigger a stop?
  2. if not possible in Pluto. Is there another option?

Here is the code for my MVP which I use in Pluto (sorry, I don’t know how to include the Pluto cells appropriately here).

# Cell1
using Plots, PlutoUI

# Cell2
rectangle(w,h,x,y) = Shape(x .+ [0,w,w,0], y .+ [0,0,h,h] );

# Cell3
function animated_bar(xpos)
	p = plot( xlims=(1,100), ylims=(1,100), axis=nothing, legend=false, label=false)
	square = rectangle(4,4,rand(1:100),rand(1:100))
	bar = rectangle(10,3,xpos,4)
	plot!(square, c=:red)

# Cell4
@bind xpos PlutoUI.Slider(1:100, default=50)

# Cell5

In the end I wanted to implement simple games like brickbreaker in Pluto. I believe it is a great usecase to show how great Pluto is…

Thanks for your help!{Function,%20Real}

Thanks for your suggestion. I have played around with it but did not manage to get it working via Base.Time. Could you give me a hint how you would structure my above code to include Base.Timer in a reasonable way.

My goal is to have the square move around deterministically (a function moving the square) all the time. Then the bar is only moved when a user is using the slider to indicate the position on the x-axis.

While I know how to achieve both separately

  • square: use while true…
  • bar: just use a Slider

I cannot achieve both together.

Any further hint will help! Thanks!

If the while loop works for you, then you may not need a timer, but at least put a sleep in the while loop so that other code has a chance to run. You want to encapsulate the state for drawing a frame, such as the square and bar coordinates, in a mutable struct. Both the slider handling code and the square loop need a reference to the frame state struct. The square loop updates the square coordinates and replots. The slider handler updates the bar coordinates and replots explicitly on events. Replotting draws both the bar and square from the values in the struct.

Thanks for your reply. I will have another look at this. Although I just realized that a while loop works (e.g. in Jupyter Notebook or VS Code), however, not in Pluto given the plot is only updated at the end. I will try some other approaches and post my code in case I still struggle.

Thanks again for your help!