clojure - How to prevent overlapping animations using core.async? -
i have loop handling animations character -- set-image!
takes key , displays appropriate image.
(defn main-animation-loop [] (go (while true (set-image! :normal) (<! (timeout 8000)) (set-image! :blink) (<! (timeout 150)))))
every once in while character needs special actions. should able interrupt main animation:
(defn dance! [] (go (set-image! :look-left) (<! (timeout 1000)) (set-image! :look-right) (<! (timeout 1000)) (set-image! :wave) (<! (timeout 2000))))
what's way pause main animation while dance routine happening?
it's common in csp style programming pass control channel event loops can, @ least tell them when stop. in case if there control channel went main-animation-loop
, gave copy of dance!
, dance tell main-animation-loop
pause , unpause appropriatly. or stop start again (passing same control channel in case others using it).
i use pattern check messages each time around event loop:
(go (while (not= control-chan (second (async/alts! [control-chan (async/timeout arg)]))) (do-stuff-here))
this checks see if timeout or control channel caused interruption.
(defn main-animation-loop [control-chan] (go (while (not= control-chan (second (async/alts! [control-chan (async/timeout 150)]))) (set-image! :normal) (<! (timeout 8000)) (set-image! :blink)))) (defn dance! [control-chan] (go (!> control-chan :stop) (set-image! :look-left) (<! (timeout 1000)) (set-image! :look-right) (<! (timeout 1000)) (set-image! :wave) (<! (timeout 2000)) (main-animation-loop control-chan)))
by passing same channel both functions, allow them communicate each other. main-animation-loop
keep looping long messages receives coming timeout channel. sees 1 of them came control channel instead of timeout, stop. allows dance!
tell stop sending message control channel. in similar code have main event loop check content of message , more stop, though in case stopping enough because dance!
can start event loop again.
Comments
Post a Comment