Thursday, July 14, 2011

Simple Tween Engine For AS2

Copy this code and add to Frame 1 of Scene:

//time: seconds: 0.5 means: .5s
//att: object contains {_x, _y, _xscale, _yscale, _alpha, onComplete, onCompleteParams}
_global.bEngine = new Object();

_global.bEngine.to = function (mc: MovieClip, time: Number, att: Object) {
if (mc.__bEngine_isTweening == true) {
_global.bEngine.kill(mc, false);
}
mc.__bEngine_duration = time*1000;
mc.__bEngine_isTweening == true;
mc.__bEngine_tweenAtt = new Object();
for (var ob in att) {
if (ob == "onComplete") {
mc.__bEngine_onComplete = att[ob];
} else if (ob == "onCompleteParams") {
mc.__bEngine_onCompleteParams = att[ob];
}else {
mc.__bEngine_tweenAtt[ob] = new Object();
mc.__bEngine_tweenAtt[ob]["endValue"] = att[ob];
mc.__bEngine_tweenAtt[ob]["startValue"] = mc[ob];
mc.__bEngine_tweenAtt[ob]["change"] = att[ob] - mc[ob];
}
}
mc.__bEngine_update = function() {
// get progress
var currentDuration = getTimer() - this.__bEngine_startTime;
var _progress = _global.bEngine.easeNone(currentDuration, 0, 1, this.__bEngine_duration);

if ( _progress > 1 ) _progress = 1;
for (var ob in this.__bEngine_tweenAtt) {

this[ob] = this.__bEngine_tweenAtt[ob]["startValue"] + this.__bEngine_tweenAtt[ob]["change"]*_progress;
}
//end animation
if ( currentDuration >= this.__bEngine_duration ) {
delete this.onEnterFrame;
if (this.__bEngine_onComplete != undefined) {
this.__bEngine_onComplete(this.__bEngine_onCompleteParams);
}
}
}
mc.__bEngine_startTime = getTimer();
//trace("begin tween");
mc.onEnterFrame = function() {
this.__bEngine_update();
}
}

_global.bEngine.kill = function(mc: MovieClip, forceFinish: Boolean) {
delete mc.onEnterFrame;
mc.__bEngine_isTweening == false;
mc.__bEngine_onComplete = undefined;
if (forceFinish == true) {
for (var ob in mc.tweenAtt) {
if (ob == "_x" || ob == "_y" || ob == "_xscale" || ob == "_yscale" || ob == "_alpha") {
mc[ob] = mc.tweenAtt[ob];
}
}
}
}


_global.bEngine.easeNone = function(t:Number, b:Number, c:Number, d:Number):Number { return c*t/d+b; }
//function easeIn(t:Number, b:Number, c:Number, d:Number):Number { return c*(t /= d)*t*t*t*t+b; }
//function easeOut(t:Number, b:Number, c:Number, d:Number):Number { return c*((t=t/d-1)*t*t*t*t+1)+b; }


Usage:

import mx.utils.Delegate;

_global.bEngine.to(test_mc, 1, {_x: 800, _alpha: 30,
_xscale: 30, _yscale: 30, _y: test_mc._y + 90,
onComplete: Delegate.create(this, onComplete),
onCompleteParams: [test_mc]});

function onComplete(params: Array) {
trace("onComplete: " + params[0]);
}