var Tween = function( list, attributes ) {
// this.easing = Tween.LINEAR;
this._easing = Tween.LINEAR;
this._easefn = this.lerp;
this._attr = attributes;
this._steps = [];
this._time = 0;
for (var i = 0; i < list.length; i++) {
this.addStep( list[i] );
}
};
Tween.LINEAR = 0;
Tween.CUBIC = 1;
Tween.SINE = 2;
Tween.CUSTOM = 99;
Object.defineProperty(Tween.prototype, 'easing', {
get: function() { return this._easing; },
set: function( type, fn ) {
switch (type) {
case Tween.CUBIC:
this._easing = Tween.CUBIC;
this._easefn = this.cubp;
break;
case Tween.SINE:
this._easing = Tween.SINE;
this._easefn = this.sinp;
break;
case Tween.CUSTOM:
if (typeof fn == 'function') {
this._easing = Tween.CUSTOM;
this._easefn = fn;
break;
}
default:
this._easing = Tween.LINEAR;
this._easefn = this.lerp;
}
}
});
Tween.prototype.lerp = function( a, b, alpha ) {
return a * (1 - alpha) + b * alpha;
};
Tween.prototype.cubp = function( a, b, alpha ) {
alpha = (-2 * alpha + 3) * alpha * alpha;
return this.lerp( a, b, alpha );
};
Tween.prototype.sinp = function( a, b, alpha ) {
// return (a - b) / 2 * (Math.cos(Math.PI * alpha) - 1) + a;
alpha = 0.5 * Math.sin( (alpha - 0.5) * Math.PI ) + 0.5;
return this.lerp( a, b, alpha );
};
Tween.prototype.addStep = function( step ) {
if (step.length !== 2) {
console.error( "Invalid Tween step" );
return;
}
for (var i = 0; i < this._steps.length; i++) {
if (this._steps[i][0] > step[0]) {
this._steps.splice( i, 0, step );
return;
}
}
this._steps.push( step );
};
Tween.prototype.value = function( time ) {
if ( typeof time != 'number' ) {
time = this._time;
}
if ( time <= this._steps[0][0] ) {
return this._steps[0][1];
}
if ( time >= this._steps[ this._steps.length - 1 ][0] ) {
return this._steps[ this._steps.length - 1 ][1];
}
for (var i = 1; i < this._steps.length; i++) {
if ( time === this._steps[i][0] ) {
return this._steps[i][1];
}
if ( time < this._steps[i][0] && time > this._steps[i - 1][0] ) {
var start = this._steps[i - 1],
end = this._steps[i],
alpha = ( time - start[0] ) / ( end[0] - start[0] );
var value = {};
for (var i = 0, a; i < this._attr.length; i++) {
a = this._attr[i];
value[a] = this._easefn(start[1][a], end[1][a], alpha);
}
return value;
}
}
return {};
};
Tween.prototype.update = function( dt ) {
this._time += dt;
return this.value( this._time );
};
The timing functions may be unnecessary.