Getting Started Tweening with GSAP for Flash

January 1st 2012 | Carl
favorite

78502

Quick links

Introduction

Animating with code may seem intimidating at first, but don't worry - you'll get the hang of it quickly. The GreenSock Animation Platform (GSAP) was engineered to make it simple and intuitive. For now, we'll focus on getting you up and running with the core engine, TweenLite, and then we'll discuss if and when you might want to put the other tools to work for you (like TweenMax, TimelineLite, TimelineMax, etc.).

Installing the code

Go to the GSAP product page and click the "download" button to download a zip file containing the entire GreenSock Animation Platform in the language you specified. Unzip the file and you'll see a folder containing several swfs, documentation, and a folder named "com" - that's the critical one. Take that "com" folder with all its contents and drop it into the same folder as your FLA file (or if you're an advanced user, set up a classpath to wherever you want). Make sure that you leave the directory structure inside the "com" folder in-tact; it has a "greensock" folder with several ActionScript files inside, along with a few subdirectories.

You can throw away the swfs from the zip download and the documentation, etc. if you want. The only critical files are inside that "com" folder.

When you publish your swf, Flash looks for that "com" folder, reads the code from inside of it, and embeds it into your published swf. You do NOT need to put the "com" folder on your web server. Once the swf is created, it is completely independent and has no dependencies on the class files because they have been embedded into the compressed swf. Your FLA file has the dependencies, not the swf.

There's a great ActiveTuts article here about using 3rd party tools in your Flash projects and it covers some of the more advanced installation/configuration options.

Importing

In order for Flash to understand what you mean when you type "TweenLite" (or "TweenMax" or any of the GreenSock classes), you must tell it where to find the class file(s). That's what an import statement does. It acts as a pointer that tells Flash where it should look. After all, there could be a completely different "TweenLite" class that another author created, and you need a way to tell Flash which one you're talking about. Typically you put your import statement at the top of the frame or the custom class you created. And, yes, just like any class, you must add the import statement to all frames or classes that contain code referencing it. This does not add extra kb to your file every time you import it. Flash is smart enough to embed it once and all the import statements just act as a "pointer" to the embedded class.

To import just the TweenLite class, do:

import com.greensock.TweenLite;

To import TweenLite and TweenMax, do:

import com.greensock.TweenLite;
import com.greensock.TweenMax;

To import all of the classes in the com.greensock package (don't worry, Flash will only embed the classes that you actually use in your code), do:

import com.greensock.*;

You'll probably also want to import the easing classes as well (we'll talk more about them later), so this is code that you should get used to putting at the top of your frames or class files because it covers almost everything you'd need and it's shorter than typing out each class every time:

import com.greensock.*;
import com.greensock.easing.*;

Basic tweening with TweenLite

Each tween you create needs a target (the object you want to tween), the duration of the tween (typically described in seconds), and the properties that you want to tween, along with their corresponding end values. Let's say, for example, you have a MovieClip named "mc" and you'd like to tween its x property to a value of 100 (sliding it across the screen) over the course of 1.5 seconds. You can use TweenLite's to() method to do it:

TweenLite.to(mc, 1.5, {x:100});

The first parameter is the target, the second is the duration, and the third is an object with one or more properties that correspond to your target object's properties. Since it's a to() tween, you're telling TweenLite to tween from whatever the x property happens to be at the time the tween begins (now in this case), to a value of 100. If you want to also tween the y property to 200 and the alpha property to 0.5, you'd do:

TweenLite.to(mc, 1.5, {x:100, y:200, alpha:0.5});

There is no limit to the number of properties you can tween. And TweenLite can tween any numeric property of any object, not just a predetermined list of DisplayObject/MovieClip properties. Since there's an AS2 version as well, you can simply change the property names to reflect their AS2 equivalents, like:

TweenLite.to(mc, 1.5, {_x:100, _y:200, _alpha:50});

Here's an interactive demo that allows you to build tweens yourself and see the corresponding code at the bottom:

Get Adobe Flash player

There is also a very useful from() method that allows you to define the starting values in the tween and go backwards. So the current values will be used as the end values, and the ones you define in the tween will be the starting values. This makes it easy to, for example, set things up on the stage where you'd like the objects to end, and then animate them into place. Let's say your mc object's y property is at 200 and alpha is at 1, and you'd like to have it "drop" into place from above while fading in over the course of 1.5 seconds, you could do:

TweenLite.from(mc, 1.5, {y:0, alpha:0});

If you prefer a more object-oriented approach and/or would like to store references to your tweens in variables so that you can control them later (for example, pause(), resume(), reverse(), restart()), you can create a tween like this (which is identical to a to() tween):

var myTween:TweenLite = new TweenLite(mc, 1, {x:100, y:200, alpha:0.5});

Special properties

A special property is a reserved keyword that TweenLite recognizes and handles differently than it would a normal property. One example is delay which allows you to delay a tween from starting until a certain number of seconds has elapsed. For example, this tween will wait 2 seconds before beginning:

TweenLite.to(mc, 1, {x:100, delay:2});

TweenLite recognizes several special properties that are quite useful, like onComplete, ease, overwrite, paused, useFrames, immediateRender, onStart, onUpdate, onCompleteParams, and more. Please read the full documentation for details. Two of the most common special properties you'll likely use are ease and onComplete. To alter the rate of change during a tween, you can choose from many different easing equations from either the com.greensock.easing package or Flash's own easing classes or Robert Penner's. The interactive demo above allows you to chose different equations and see how they affect the tween. The onComplete special property gives you a way to call any function when the tween completes, making it simple to create a chain of events.

Here is a tween that uses the Elastic.easeOut ease, delays its start time by 0.5 seconds, and calls myFunction() when it completes:

TweenLite.to(mc, 1.5, {x:100, ease:Elastic.easeOut, delay:0.5, onComplete:myFunction});
function myFunction():void {
    trace("tween finished");
}

Plugins

Think of plugins like special properties that are dynamically added to TweenLite (and/or TweenMax), giving it extra abilities that it doesn't normally have by default. Each plugin is associated with a property name and it takes responsibility for handling that property. For example, the FrameLabelPlugin is associated with the frameLabel property name so if it is activated it will intercept the frameLabel property in the following tween and manage it uniquely:

TweenLite.to(mc, 1, {frameLabel:"myLabel"});

If the FrameLabelPlugin wasn't activated, TweenLite would act as though you were trying to literally tween the mc.frameLabel property (and there is no such thing).

Activating a plugin requires a single line of code and you only need to do it once in your application, so it's pretty easy. Simply pass an Array containing the names of all the plugins you'd like to activate to the TweenPlugin.activate() method, like this:

import com.greensock.plugins.*;
TweenPlugin.activate([FrameLabelPlugin, ColorTransformPlugin, TintPlugin]);

To make it even easier, I created the Plugin Explorer which writes the code for you. All you need to do is select the plugins and copy/paste the code from the bottom of the tool. It also displays interactive examples of each plugin and the assocaited code so that it's easy to see the correct syntax.

Get Adobe Flash player

TweenLite does not activate any plugins by default, but TweenMax does. When a plugin is activated, it affects both TweenLite and TweenMax.

Overwriting other tweens

An often overlooked aspect of tweening is how (and if and when) tweens overwrite other tweens of the same object. For example, let's say you have a button with ROLL_OVER and ROLL_OUT handlers that tween its alpha higher on ROLL_OVER and lower on ROLL_OUT. To further complicate things, let's say the ROLL_OVER tween lasts 2 seconds and the ROLL_OUT tween lasts 1 second. What should happen if the user rolls over/out/over/out quickly? See the problem? If tweens are allowed to run without any kind of overwriting, they'll build up and fight with each other (one trying to tween the alpha higher, and the other lower). In this example, when the user rolls over, a 2-second tween would start increasing the alpha to 1, but if the user rolled off 0.2 seconds later, another tween would begin, causing the alpha to decrease. When that tween finishes 1 second later, the ROLL_OVER tween is still going (since it had a duration of 2 seconds), so the alpha would suddenly jump up and finish off at a value of 1 even though the user rolled out!

Don't worry. We've got you covered.

By default, whenever a TweenLite instance renders for the first time (after any delay), it analyzes all other active tweens of the same target and checks for individual overlapping properties. If it finds any, it kills the offending overlaps (again, only the individual properties). This overwrite mode is called "auto" and it is typically the most intuitive. However, there may be times when you want the new tween to kill all other tweens of the same object regardless of their start times or overlapping properties. That is what the "all" overwrite mode is for. And to skip overwriting altogether, you can define an overwrite mode of "none". There are several other modes to choose from too, so check out the full docs for details. You define an overwrite mode with the overwrite special property like this:

//overwrites all tweens of mc immediately
TweenLite.to(mc, 1, {x:50, overwrite:"all"});

//doesn't overwrite anything (allows conflicts)
TweenLite.to(mc, 1, {x:50, overwrite:"none"});

//overwrites only individual overlapping properties on concurrent tweens of mcmyElement (this is the default, so you typically don't need to specify any overwrite in this scenario)
TweenLite.to(mc, 1, {x:50, overwrite:"auto"});

//set the default overwrite mode to "all" instead of "auto"
TweenLite.defaultOverwrite = "all";

Of course you can manually kill all the tweens of a particular object using the TweenLite.killTweensOf() method, but the nice thing about defining overwrite modes is that the overwriting doesn't kick in until it's necessary (when the tween renders for the first time) which is essential when working with complex sequences.

Controlling tweens

Once a tween is created, you may want to pause(), resume(), reverse(), play(), restart(), invalidate(), or kill() it. It's pretty easy, actually:

var myTween:TweenLite = new TweenLite(mc, 1, {x:100, y:100});

//pause
myTween.pause();

//resume (honors direction - reversed or not)
myTween.resume();

//reverse (always goes back towards the beginning)
myTween.reverse();

//play() (always goes forwards)
myTween.play();

//restart
myTween.restart();

//invalidate (clears out any starting values that were recorded and forces the tween to re-initialize on the next render)
myTween.invalidate();

//kill the tween immediately
myTween.kill();

//kill all tweens of the mc object
TweenLite.killTweensOf(mc);

TweenMax has some additional static methods for getting all the tweens of a particular object, pausing them all, resuming, getting tweens of objects that are children of a certain DisplayObject, and more (see documentation for details).

Which class do I use? TweenLite? TweenMax? TweenNano?

If you can afford the file size (roughly 23kb with the default plugins), just use TweenMax. It is the most full-featured tweening engine and it automatically handles activating a bunch of useful plugins by default, so it makes things very easy. If, however, you're concerned about file size and want precise control over which plugins get activated, TweenLite is for you. It's amazingly capable for its size and has all the essentials crammed into about 8kb. It is really the core of the whole platform and has become incredibly popular. If you simply must shave off another 6k and are willing to sacrifice quite a few features (most notably lack of support for plugins and insertion into TimelineLite/Max instances), use the ridiculously small 2k TweenNano. I would strongly recommend sticking with TweenLite or TweenMax if you can, though, because they offer much more flexibility than TweenNano. All of the engines use exactly the same syntax, so these lines will produce identical results:

TweenNano.to(mc, 1.5, {x:100, y:200, onComplete:myFunction, ease:Strong.easeOut});
TweenLite.to(mc, 1.5, {x:100, y:200, onComplete:myFunction, ease:Strong.easeOut});
TweenMax.to(mc, 1.5, {x:100, y:200, onComplete:myFunction, ease:Strong.easeOut});

Keep in mind that TweenMax extends TweenLite, so it does everything TweenLite does, plus more. And the plugins that are activated by default in TweenMax can also be activated in TweenLite (the only exception being roundProps), so with a couple of extra lines of code at the start of your application, TweenLite can have many of the same capabilities as TweenMax (activating plugins increases the file size beyond 4.7k obviously). There are several features that are only available in TweenMax, though, so check the documentation.

Sequencing and grouping tweens with TimelineLite

Unlike most other scripted animation tools, sequencing in GSAP is much more flexible than building a queue of tweens that run one-after-the-other. You have complete control over the relative timing of each tween - they can overlap as much as you want. And you can control entire sequences as a whole, reverse smoothly anytime, jump to any point, adjust the timeScale(), etc. and everything renders in the proper order.

Watch this video for a visual demo showing how TimelineLite can save you a lot of time. Although the video uses the HTML5/JavaScript version of GSAP, the same concepts apply to ActionScript.

Of course you could sequence tweens by using the delay special property on all your tweens, but that can get complicated when you build a long sequence and then later want to change the timing of something early in the sequence (you'd have to adjust all the delay values in tweens after that). Plus it would be a pain to control the whole sequence, like to pause() or resume() or reverse() the group on-the-fly. Sequencing is much easier with TimelineLite and its big brother, TimelineMax.

Let's jump into some sample code:

//create a TimelineLite instance
var tl = new TimelineLite();

//append a to() tween
tl.to(mc, 1, {x:50});

//add another sequenced tween (by default, tweens are added to the end of the timeline which makes sequencing simple)
tl.to(mc, 1, {height:300p, ease:Elastic.easeOut});

//offset the next tween by 0.75 seconds so there's a gap between the end of the previous tween and this new one
tl.to(mc, 1, {alpha:0.5}, "+=0.75");

//overlap the next tween with the previous one by 0.5 seconds (notice the negative offset at the end)
tl.to(mc, 1, {rotation:360}, "-=0.5");

//animate 3 MovieClips (mc1, mc2, and mc3) to a rotation of 60 degrees, and stagger their start times by 0.2 seconds
tl.staggerTo([mc1, mc2, mc3], 1, {rotation:60}, 0.2);

//then call myFunction()
tl.call(myFunction);

//now we can control the entire sequence with the standard methods like these:
tl.pause();
tl.resume();
tl.restart();
tl.reverse();
tl.play();

//jump to exactly 2.5 seconds into the animation
tl.seek(2.5);

//slow down playback to 10% of the normal speed
tl.timeScale(0.1);

//add a label named "myLabel" at exactly 3 seconds:
tl.add("myLabel", 3);

//add a tween that starts at "myLabel"
tl.add( TweenLite.to(mc, 1, {scale:0.5}), "myLabel");

//jump to "myLabel" and play from there:
tl.play("myLabel");

Think of a timeline (as in a TimelineLite or TimelineMax instance) like a collection of tweens that are positioned at specific places on that timeline. It controls their playback. Timelines can be nested inside other timelines as deeply as you want. This is a very powerful concept because it allows you to control entire sequences in a modular way. Imagine 100 characters individually animating into place in a staggered fashion (100 tweens). They could all be grouped into a TimelineLite instance and then controled as a whole (using common methods like pause(), resume(), reverse(), restart(), etc.). In fact, you could create functions that return animations wrapped in a TimelineLite so that you can easily build a larger, more complex animation in a modular way.

A central concept to grasp is that every tween is inserted into a timeline. By default, it's the root timeline inside the engine. When a timeline is playing, its virtual playhead advances. If you reverse() a timeline, the playhead travels in the opposite direction back towards its beginning. As the timeline's playhead encounters tweens, it plays them accordingly. For example, if the playhead is positioned halfway through a tween, that tween will render as though it is 50% finished. If the timeline's timeScale() is set to 0.5, that would cause the playhead to travel at half speed. Consequently, any tweens it encounters would also appear to progress at half speed. Once you get the hang of how timelines work, they can revolutionize your animation workflow.

Just like tweens, timelines play immediately by default but you can pause them initially using pause() or by setting paused:true in the vars parameter of the constructor.

There are quite a few methods available in the timeline classes that give you precise control, and we'd encourage you to look through the docs to see what's available. If you can think of something you'd like to do, chances are there's a way to do it.

Just like the way TweenMax extends TweenLite, TimelineMax extends TimelineLite, using identical syntax and adding several useful (but non-essential) features like AS3 event dispatching, repeat(), repeatDelay(), getActive(), getLabelAfter(), getLabelBefore(), currentLabel(), and more. Please refer to the TimelineMax documentation for details. Here's an interactive demo of TimelineMax:

Get Adobe Flash player

Need help?

Feel free to post your question on the forums. Keep in mind that you'll increase your chances of getting a prompt answer if you provide a brief explanation and include a simplified FLA file (and any class files) that clearly demonstrates the problem.


Get GSAP

Version: 1.19.0 updated 2017-01-17

Core

    Extras

      Plugins

        By using GreenSock code, you agree to the terms of use.

        Help support GreenSock by becoming a member

        Join Club GreenSock