So I ran into a bit of a snag yesterday when I was working for the first time with the most excellent Greensock TweenLite ActionScript class. Naturally I panicked and blamed everything on the class. Fortunately the author of the class, Jack Doyle was listening in on his forums and responded to my surprise within minutes of my posting the query there. He assured me that his class was iron-tight and pointed me in a direction that led me to uncover the error of my ways.
How naive I was! Ah, the shame of it all.
So, to hopefully forestall any future embarassment on the part of you, my reader, who has miraculously stumbled upon this obscure piece of flotsam in the vast ocean that is the InterMegaWeb, let me expound upon the dangers of ActionScript’s pass-by-reference.
But first, let me set the stage by introducing TweenLite a little. Although the class has absolutely no bearing whatsoever on the problem I was experiencing, the way the class is designed kind of allows one to fall into the trap fairly easily, and makes a good example. And besides, it’s a very useful class, so if this is your first introduction to it, I will consider that I did you a service.
TweenLite serves to bolster ActionScript support for tweening things over time without using the Timeline or the Flash IDE. For those of us foolish enough to try to animate things using code, the built-in native Flash Tween class is woefully poor, performance-wise. There are tests to prove it (beware: when testing the native Flash Tween class, be sure to lower the values as it will crash your browser – that’s just how bad the Flash class is!). The TweenLite tween class is a joy to use.
Let’s say you want to tween a MovieClip named myClip across the stage from x = 100 to x = 500, and from y = 100 to y = 400, and you want it done over 5 seconds:
TweenLite.to(myClip, 5, {x:500, y:400});
The previous example assumes that myClip is already at x = 100 and y = 100. Over the next 5 seconds, it will move its way toward (500,400) incrementally each frame. You don’t have to do a damned thing but sit back and watch. Very sweet.
You can even add other, custom parameters to TweenLite to tweak its behaviour. Say you wanted a 1-second delay before the object actually started to move:
TweenLite.to(myClip, 5, {x:500, y:400, delay:1});
Simple. And then of course I had to get in there, try to make things even more user-friendly and that’s when stuff starting blowing up.