Skip to content

Instantly share code, notes, and snippets.

@pushcx
Last active December 20, 2015 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pushcx/6205039 to your computer and use it in GitHub Desktop.
Save pushcx/6205039 to your computer and use it in GitHub Desktop.
# an interative animation queue for Crafty
Crafty.c "AnimationQueue",
init: ->
@requires("Tween")
@step_done_callback = undefined
# animations should be an array of hashes with the keys
# tween: a hash that gets passed to tween()
# frames: number of frames, passed to tween()
# callback: optional, a callback to run after this step completes
# done is a callback to run when all steps are completed
animate: (animations=[], done) ->
@animation_queue ||= []
Array::push.apply @animation_queue, animations
# all done callbacks will fire, even if animate() is called multiple times
# before finishing. Queueing a new animation from a callback results in
# that callback executing immediately, because the queue is in the middle
# of finishing. Use window.setInterval(function () {foo.animate(...)}, 0)
# to queue after your callback is done.
@done_callbacks ||= []
@done_callbacks.push done if done
# unbind any existing copies of our callback so that multiple calls to
# animate() don't trigger multiple step endings
@unbind('TweenEnd').bind 'TweenEnd', (property) =>
# ignore TweenEnd for anything else
return unless property == 'AnimationQueueStepDone'
@step_done_callback() if @step_done_callback
@step_done_callback = undefined
if @animation_queue.length == 0
done() for done in @done_callbacks
@done_callbacks = []
return
# pop off next animation
next = @animation_queue[0]
@animation_queue = @animation_queue[1..]
# get the next animation tweening
next.tween['AnimationQueueStepDone'] = true
@tween(next.tween, next.frames)
@step_done_callback = next.callback
# dummy animation to kick off TweenEnd callback loop
@trigger('TweenEnd', 'AnimationQueueStepDone')
this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment