Skip to content

Instantly share code, notes, and snippets.

@stefanoortisi
Last active December 21, 2015 05:19
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 stefanoortisi/6256159 to your computer and use it in GitHub Desktop.
Save stefanoortisi/6256159 to your computer and use it in GitHub Desktop.
Tweener Coffescript Class
###
An utility object which allows to create different animations with different keyframes.
The get_value method return the interpolated value of the selected animation depending on time parameter.
###
class Tweener
constructor: ->
@keyframes = new Object()
add_keyframe: ( name, data, reset = false ) ->
if reset
@keyframes[name] = []
else
@keyframes[name] ?= []
unless data.hasOwnProperty('ease')
data.ease = 'linearNone'
@keyframes[name].push data
get_value: (name, time) ->
return unless @keyframes[name]?
@data = @keyframes[name]
index_key_1 = @get_ending_keyframe time
index_key_0 = index_key_1 - 1
key_1 = @data[index_key_1]
key_0 = @data[index_key_0]
max_time = key_1.time - key_0.time
the_time = time - key_0.time
max_value = key_1.value - key_0.value
x = Easie[ key_0.ease ]( the_time, key_0.value, max_value, max_time )
#x = max_value * the_time / max_time + key_0.value
return x
get_ending_keyframe: (time) ->
l = @data.length
for index in [ 1 ... (l - 1) ]
if @data[index].time >= time
return index
return l - 1
# Note: You need to import Easie.coffee (https://github.com/jimjeffers/Easie)
# Create the object
@tweener = new Tweener()
# Adding some animations with their different keyframes
@tweener.add_keyframe('my_animation', { time: 0, value: 20, ease:'quadIn'})
@tweener.add_keyframe('my_animation', { time: 0.3, value: 50, ease:'quadIn'})
@tweener.add_keyframe('my_animation', { time: 0.6, value: 100, ease:'quadIn'})
@tweener.add_keyframe('my_animation', { time: 1, value: 80, ease:'quadIn'})
@tweener.add_keyframe('other_animation', { time: 0, value: 50})
@tweener.add_keyframe('other_animation', { time: 1, value: 10})
# Get the interpolate value passing the aniamtion name and the time as a paramenters
interpolated_value = @tweener.get_value 'my_animation', 0.8
other_interpolated_value = @tweener.get_value 'other_animation', 0.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment