Chain Tween (3)

, under actionscript, Code snippets.

ChainPrevious year I was working on a little class called Chain. Chain is a delayed function-calling util class for AS3. Now I was already working at a updated version which could animate too (see this tweet from last year). Basically it has become a small tween engine. You have to know there are much better tween engines, like TweenLite, Tweener, eaze tween, gtween etc.. So you don’t need a new tween engine, and definitely not this one 🙂 I just love to share some thoughts.

I just finished this to see how far I could come and where I have to deal with by creating such an engine. It is just fun to develop classes which will bring you to a higher level of coding, because I really want to become an actionscript sensai master or something. When starting the animation part, I was very inspired by this post, which has the same idea of combining jQuery-syntax-style with tweening, which I was already using in Chain.
Making a class chainable is very easy, you just have to return the class instance on every public function, like this:
[as]package
{
public class ExampleChain
{
public function add():ExampleChain
{
trace(this, “saying hi!”)
return this;
}
}
}
[/as] This already allows you to do this:[as]
var chain:ExampleChain = new ExampleChain();
chain.add().add().add().add();
[/as]I think this is very powerful and we should use more chaining.

Anyway, Chain was originally created to make delayed function calling. I wrapped code around this feature, so it is still usable like it was intended, only I improved some functions and added tweening. You can pass a complete handler to the play() function. And it is also possible to reverse the full chain, even with animation.

Here again, the original simple usage
[as]
var myChain:Chain = new Chain();
myChain.add(one, 2000)
.add(two, 500)
.add(three, 1000)
.play(3, onChainComplete); // play 3 times

// some functions
function one():void { trace(“one”) }
function two():void { trace(“two”) }
function three():void { trace(“three”) }
function onChainComplete():void {
trace(“done.”);
myChain.destroy();
}
/* trace output:
one two three one two three one two three done.
*/
[/as]

Animated chain example
[as]
var myChain:Chain = new Chain();
myChain
.animate(myMc, {x:300,y:100}, 700, Easing.elasticInOut)
.wait(200)
.animate(myMc2, {rotation:100, alpha:0.5}, 500, Easing.quartIn)
.wait(200)
.play(2, onChainComplete); // play 2 times

function onChainComplete():void {
trace(“done.”);
myChain.destroy();
}
[/as]
As you can see, you can still chain things, it animates multiple movieclips, and it can be played multiple times. It is very readable, which I really like. It works also in reversed order too, so you can reverse the full animation (pointless but cool)!

If you don’t want to animate, but instantly apply settings to a displayObject,
you can use apply(mc, {vars}), of couse this equals animate(mc,{vars},0) but it is more elegant.

To control the Chain, you have can use:
stop() Stop playing, use doContinue to play futher from current point
doContinue() Continue playing after a stop
reset() Reset indexes, start from first point. If reversed, start at last point

So how does it work? Well it is still based on the same old add() function. When you call the animate() function, internally, it is collecting the properties of the tween. Then it is calling the add() function, with a reference to a protected function playTween(), which is always the same. So when you play the chain, it just calling a local function every time, which handles the animation.

For now, I don’t have any special properties; no auto-alpha, no short-rotation, blurfilters or tinting etc. You can only animate properties of movieclips.

So how does tweening (animation over time) work? This is the formula I am using:
[as]_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(currentTime – _startTime) / _duration);[/as]
This needs a little explanation. For example: When you add {x:100} as object to Chain for animation, “x” is the property.name, and 100 is the property.endValue. I am also getting current “x” value of the displayobject (which should move); this is the property.startvalue. Imaging this is currently 75.
If you would write down the values into the formula, it looks like this:
[as]myMc[“x”] = 75 + ((100 – 75) * _easeFunc(currentTime – _startTime) / _duration));[/as]
Now, as you can see, this is more readable. The only thing that is still vague is the ease function. Now I have to say this was a bit hard for me to understand at the first time, but it became very clear when I did understand what is does. I have read the book ‘Making things move’ from Keith Peters (aka bit-101), which is a great reference and eye opening book for programmatic animation, trigonometry and other cool stuff. There is a chapter where animation over time is explained, which was really helpful creating the tween engine, and this time calculation. Now the time calculating returns a ratio, which is needed for the easing functions. I also studied some famous other tween engines; most of them use basically the same formula. By the way, the easing equations are used from Robert Penner.

Now, I really wanted to reverse the animations too. After some headache, the solutions was very simple. The time calculation is a value between 0-1, so I did 1 minus the time ratio 🙂
[as]_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(1 – (currentTime – _startTime) / _duration));[/as]

Another problem I had to deal with was the fact that animating 1 thing at a time is very boring. So I invented the animateAsync(), which works almost exactly like the animate(), only you could pass the duration and the delay as separate values. So you can move a clip for 700 milliseconds, and call the next chained item after 75 milliseconds. To compare: when using the animate() function, if you move an item for 700 milliseconds, it will take 700 milliseconds when calling the next chained item. This could cause strange behaviors and isn’t easy to manage (especially when you want to wait till all animations are done), but I its a nice feature I think. Again, even the async’s can be played in reversed order.
[as]
var myChain:Chain = new Chain();
myChain
.animateAsync(myMc, {x:300,y:100}, 700, 10, Easing.elasticInOut)
.animate(myMc2, {rotation:100, alpha:0.5}, 500, Easing.quartIn)
.wait(200)
.play(2, onChainComplete); // play 2 times

function onChainComplete():void {
trace(“done.”);
myChain.destroy();
}
[/as]
To clear all references, you should call the myChain.destroy(); function. This clears the references to all added functions, and clears the internal tween list.

update 02/11/2010:
– added show/hide/rotate function
– added shortRotation option
– added scale (no need to define scaleX and scaleY separately)
– optimized chain; chain items are stored by duration inside dictionary to save lots instances (where duration is the same)
– added Chain.create for fast creation of an instance
– updated apply function (extra param; apply on start)
– several coding style fixes
– added destroyOnComplete to animate() function

So if you are interested in the code, you can find it inside my googlecode:
» Chain Tween sources

3 responses to “Chain Tween”

  1. Matt says:

    Cool idea thanks for sharing. I dig the explaination of the tweening formula – I’ve wondered how they work but never took them apart.

  2. mnemonic says:

    when i using “.add(func1,1000)” function, how can i pass variabel into func1 parameters?

  3. Mark says:

    @mnemonic you could update the add function, where you pass parameters as an array. You also have to store that in the internal ChainItem class. Then in the Chain.execute function, you should replace obj.func(); with something like this:

    if (obj.params)
    obj.func.call(null, obj.params);
    else
    obj.func();

Say something interesting

Please link to code from an external resource, like gist.github.com.