An Introduction to Tweening with ActionScript 3.0

Oct 9th in ActionScript, Novice by Daniel Apt

Flash is known for delivering rich interactive experiences with a lot of "eye-candy". Often, this eye-candy is achieved by means of animation and Flash has great animating capabilities. During this tutorial we'll discuss tweening; Flash's automated animation.

PG

Author: Daniel Apt

Hi there, I'm Daniel! I'm a 17-year-old Dutch web designer. I have a passion for all forms of design. I've been working with Flash for 5 years.

Introduction

In this tutorial I'll discuss the following:

  • What is a tween?
  • Using the Tween class.
  • Tips & tricks for using the Tween class.
  • Third party tweening classes.

Step 1: What is a Tween?

Wikipedia explains tweening as the following:

Inbetweening or tweening is the process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image. Inbetweens are the drawings between the keyframes which help to create the illusion of motion. Inbetweening is a key process in all types of animation, including computer animation.

Most people, who have ever used Flash, have encountered a tween before. Since the early beginning of Flash, there's been the possibility to tween by using the timeline.

We won't be discussing how to tween using the timeline, we'll discuss how to tween using ActionScript 3.0!

Step 2: The Tween Class

The Tween class is the class which handles all the animation, and can animate all properties that have a numeric value. These properties could be:

  • x position
  • y position
  • alpha (opacity)
  • etc

Even though the Tween class is mostly used to animate display objects (objects that can be seen), you can use it just as effectively to tween (for example) the volume of a sound channel.

Step 3: Syntax of the Tween Class

The constructor of the Tween class is pretty lengthy, but don't worry, it's very simple.

var tween:Tween = new Tween(obj:Object, prop:String, func:Function, begin:Number, finish:Number, duration:Number, useSeconds:Boolean = false)

Let's go through the parameters one by one. We want to fade in a movie clip named square as an example. OK, let's do this:

  • The first parameter is the object that we'll be tweening, this could be a movie clip named square.
  • The second parameter is the property that we'll be tweening. This property must be a string, so if we're tweening the alpha of our square we'd use "alpha".
  • The third parameter is the transition that the tween will use. A transition gives us more control about how the tween will animate the property (eg.) that it gradually speeds up. We'll discuss transitions in the next step.
  • The fourth parameter is the value that the property starts at. If we'd fade something in, then the alpha would start at 0 (or else we would already see the square).
  • The fifth parameter is the value that the property ends with. We're fading our square in, so at the end the alpha will be 1 (1 alpha = 100% opacity).
  • The sixth parameter is the duration of the tween. This can be in frames, or in seconds. By default the duration is measured in frames.
  • The seventh and final parameter is a boolean. This boolean defines if we want to use seconds as the measurement of duration. If it's true, then the duration is measured in seconds. By default this parameter is false.

Step 4: Transitions

Transitions have already been mentioned in step 3, however let's go into more detail. A transition is a function, which describes how a property moves towards an end value. These transitions can also create certain effects, for example a bounce, or an elastic effect.

There are loads of transitions, and they've been split in to several classes as follows:

  • Back
    the transitions make the object go back, before tweening to the end value. Think of a catapult, it starts at 0, pulls back to -20 and afterwards shoots forward to 200.
  • Bounce
    the transitions make the object bounce.
  • Elastic
    the transitions make the object seem elastic.
  • None
    the transitions do nothing, the property reaches the end value in a constant motion.
  • Regular
    the transitions have a small build up to a constant speed. Think of a car, it must first accelerate before getting to speed.
  • Strong
    the transitions have a much larger build up to a constant speed. Think of a space shuttle, it also accelerates, but for much longer.

Step 5: easeIn, easeOut and easeInOut

So what do you do if you don't want to gradually accelerate, but gradually slow down? All transition classes have three functions:

  • easeIn
    the transition affects the property at the beginning.
  • easeOut
    the transition affects the property at the end.
  • easeInOut
    the transition affects the property at the beginning and end.

These transitions can be drawn as a function (and with function I mean a mathematical function, a line). Look at this transition cheat sheet to get an idea of what each transition does. Some of the transitions haven't been mentioned, this is because these transitions are from the Tweener class, which I'll mention in step 18.

Just try the demo and check how each transition affects a property. This is the best way to get an idea of what transitions do to a tween.

Step 6: Our First Tween

So now let's finally get to work! We're going to create our very first tween. Draw a square and convert it to a movie clip, afterwards give it an instance name of square.

Now that we have our movie clip, let's create a tween! First we must import the necessary classes, because these aren't imported at runtime.

//import the Tween class
import fl.transitions.Tween;
//import the transitions
import fl.transition.easing.*;

Afterwards, create a variable named tween, of type Tween.

//import the Tween class
import fl.transitions.Tween;
//import the transitions
import fl.transition.easing.*;

//create a var tween
var tween:Tween;

Now pass the parameters to the constructor. The values for our parameters are:

  • The object we're tweening is square.
  • The property we're tweening is x.
  • The transition function we'll be using is: Regular.easeInOut.
  • The starting position of square will be 0.
  • The finishing position of square will be 400.
  • The tween will last 1.5 seconds.
  • So that means that useSeconds will be true.

Our code will look like this:

//import the Tween class
import fl.transitions.Tween;
//import the transitions
import fl.transitions.easing.*;

//create a var tween
var tween:Tween = new Tween(square, 'x', Regular.easeInOut, 0, 400, 1.5, true);

If you test the flash movie (Control > Test Movie), you'll see the following:

Step 7: Understanding our App

Now it's time to build our demo. As this tutorial is about tweening, I won't discuss how to create the interface, just open step7.fla, which is located in the source files.

Before we even start writing one line of code, let's look how the file is built. There are 4 layers: Actions, UI, Rabbit and BG. We'll write all our code in the layer Actions. The UI layer has all our user interface components. Take a good look at all the instance names of all the components. The rabbit layer contains a movie clip with the instance name rabbit, we'll be tweening this movie clip. The BG layer simply contains a background, which will simply do nothing. We've gotta give our lovely bunny a nice place where he can do anything he wants to, right?

Step 8: Declaring Variables

A good practice is to first declare all the (global) variables that we will use. The code has been heavily commented, to give you an idea what each variable does.

Editor's note: I'm afraid the ActionScript in this step is causing our syntax highlighter to trip Firefox up (this sometimes happens and I've no idea why). For now, it's best you download it to have a look. Sorry for the inconvenience.

As you might have noticed, we're using a two-dimensional array. If you're not yet so experienced with Arrays, check Dru Kepple's amazing tutorial about arrays - AS3 101: Arrays. This two-dimensional array contains all possible transitions.

Step 9: Adding Event Listeners

Even though we have buttons, we need to add event listeners, or else our buttons won't do anything. If you don't understand how event listeners work, or want to learn about the event framework, check my other tutorial Taking a Closer Look at the ActionScript 3.0 Event Framework.

//when tweenButton is clicked, begin animating (fire the function animate)
tweenButton.addEventListener(MouseEvent.CLICK, animate);

//when resetButton is clicked, reset all properties of rabbit (fire the function reset)
resetButton.addEventListener(MouseEvent.CLICK, reset);

Step 10: Creating the Animate Function

When tweenButton is clicked, we want to start animating. To do this, we have to perform quite a few tasks:

  • Retrieve all the values from all components.
  • Set the correct values for transitionPos and easePos.
  • Assign transition the correct function from the transitions array.
  • Make tween call its constructor and tween rabbit.
//is called by the event listener attached to tweenButton
function animate(event:MouseEvent):void {
	//retrieve the time value from timeBox
	time = timeBox.value;
	
	//retrieve the begin value from beginBox
	beginValue = beginBox.value;
	
	//retrieve the end value from endBox
	endValue = endBox.value;
	
	//retrieve the property from propertyBox
	property = propertyBox.value;
	
	//set transition to the correct value
	switch(transitionBox.value){
		case "Back":
		transitionPos = 0;
		break;
		
		case "Bounce":
		transitionPos = 1;
		break;
		
		case "Elastic":
		transitionPos = 2;
		break;
		
		case "None":
		transitionPos = 3;
		break;
		
		case "Regular":
		transitionPos = 4;
		break;
		
		case "Strong":
		transitionPos = 5;
		break;
	}
	
	//set ease to the correct value
	switch(easeBox.value){
		case "easeIn":
		easePos = 0;
		break;
		
		case "easeOut":
		easePos = 1;
		break;
		
		case "easeInOut":
		easePos = 2;
		break;
	}
	
	//set transition to the precise transition in the transitions array
	transition = transitions[easePos][transitionPos];
	
	//tween!
	tween = new Tween(rabbit, property, transition, beginValue, endValue, time, true);
}

Step 11: Creating the reset function

When resetButton is clicked, we want to reset all the properties of rabbit. This is luckily much easier than creating the animate function.

function reset(event:MouseEvent):void {
	//reset all properties of rabbit
	rabbit.alpha = START_ALPHA;
	rabbit.x = START_X;
	rabbit.y = START_Y;
	rabbit.rotation = START_ROTATION;
	rabbit.scaleX = START_SCALEX;
	rabbit.scaleY = START_SCALEY;
	rabbit.width = START_WIDTH;
	rabbit.height = START_HEIGHT;
}

Step 12: Feel Proud of Yourself!

If you did everything correctly, then you'll have successfully built the demo. Congrats, you did it!

Download the whole code and admire all that we've written:

Step 13: Wait, There's More!

Of course, knowing how to tween isn't enough. We still need to discuss the following:

  • How to tween multiple properties.
  • How to create chains of tweens.
  • How to have a delay before your tweens.
  • Third party tweening classes.

All the following examples will be done with a movie clip, with an instance name of square.

Step 14: Starting Value

Sometimes it's great to set a starting value for a tween, however most times you'll want to tween from the object's current position. Just use the object's property as the starting value.

//import necessary classes
import fl.transitions.Tween;
import fl.transitions.easing.*;

var tween:Tween = new Tween(square, "alpha", square.alpha, .75, 1, true);

Step 15: Multiple Properties

Tweening multiple properties is very easy to do, just use the constructor several times.

//import necessary classes
import fl.transitions.Tween;
import fl.transitions.easing.*;

var tween:Tween;
tween = new Tween(square, "x", Regular.easeOut, 0, 400, 1.5, true);
tween = new Tween(square, "y", Elastic.easeOut, 30, 200, 3.5, true);
tween = new Tween(square, "rotation", Bounce.easeOut, 0, 90, 3, true);

Step 16: Chain of Tweens

A chain of tweens is that there are multiple tweens, each one starting when the previous one finishes. We need to do this by using the event TweenEvent.MOTION_FINISH. This event occurs when a tween finishes tweening.

//import necesarry classes
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

//create the tweens
var tween1:Tween = new Tween(square, "x", Strong.easeInOut, 0, 400, 1.5, true);
var tween2:Tween = new Tween(square, "y", Bounce.easeOut, square.y, 200, 1, true);
var tween3:Tween = new Tween(square, "alpha", None.easeNone, square.alpha, 0, 2, true);

//prevent tween2 and tween3 to start tweening
tween2.stop();
tween3.stop();

//add event listeners to tween1 and tween 2
tween1.addEventListener(TweenEvent.MOTION_FINISH, startTween2);
tween2.addEventListener(TweenEvent.MOTION_FINISH, startTween3);

//create the functions startTween2 and startTween3
function startTween2(event:TweenEvent):void {
	//make tween2 start
	tween2.start();
}

function startTween3(event:TweenEvent):void {
	//make tween3 start
	tween3.start();
}

You can also use the event TweenEvent.MOTION_FINISH for things other than creating a chain of tweens. Think of a flash site, after a page has been tweened, a function will be called, which will load text to display.

Step 17: Tweens with Delay

Creating a tween with a delay is very similar to creating a chain of tweens. We're using a Timer, and when the event TimerEvent.TIMER occurs, then the tween will start.

//import necesarry classes
import fl.transitions.Tween;
import fl.transitions.easing.*;

//create our timer
var timer:Timer = new Timer(3000);

//start the timer
timer.start();

//create our tween
var tween:Tween = new Tween(square, "x", Strong.easeInOut, square.x, 300, 2, true);

//prevent tween from immediately tweening
tween.stop();

//add an event listener to timer
timer.addEventListener(TimerEvent.TIMER, startTween);

//create the function startTween
function startTween(event:TimerEvent):void {
	//make tween start
	tween.start();
}

Step 18: Check the Documentation

The Tween class has quite a few methods, for example the yoyo function makes the tween play in reverse. So do look at the documentation about the Tween class.

Step 19: Third Party Tweening Classes

Sometimes the Tween class is enough for your project, however using the Tween class can be quite a hassle if you're going to tween a lot of properties, have a lot of delays etc.

Luckily there are several (free) third party classes, which have much more advanced tweening capabilities. Let's look at the pros and cons of using a third party class.

The pros:

  • Development time is much faster.
  • Tweening occurs much more efficiently than the Tween class. Performance will usually be improved while using third party classes.

The cons:

  • As these classes aren't built in, you need to import them. This takes space and your flash project will need to load more (do note that currently these classes are extremely small.
  • Some classes don't have a good documentation.

The most commonly used third party tweening classes are:

I won't discuss how to use each class, just check the links and find out which works best for you.

Thank you

Thank you for reading this tutorial., I hope it's given you a thorough understanding of how to use the Tween class. It was a pleasure to write for Flashtuts+! Why not follow me on Twitter, @DanielApt?


Enjoy this Post?

We'd love your vote!

User Comments

( ADD YOURS )
  1. PG

    Raylan October 9th

    Very good article ! Explains all we need to know about the tween class ! =D

    Thanks !

    ( Reply )
  2. PG

    Dieter October 9th

    Thanks for this tut.

    ( Reply )
  3. PG

    Brian October 9th

    Awesome dude, thanks very much for that.. If anyone else wants more flash source check out my lab.. http://www.brianwiltshire.net/lab

    Thanks again, Awesome tut

    ( Reply )
  4. PG

    Miguel Reyes October 9th

    Great post!

    ( Reply )
  5. PG

    flora October 9th

    17 years !! wow!! ;)

    ( Reply )
    1. PG

      Bern October 16th

      Makes me feel old at 27…

      ( Reply )
      1. PG

        Ian Yates October 16th

        How do you think it makes me feel? 31 years and counting..

      2. PG

        Tim October 16th

        Ha! you ain’t got nothin’ – I’m almost dead – 40 mate!

    2. PG

      Daniel Apt October 16th

      Haha guys, don’t focus too much on that, there is one great majority with being older:

      Authority.

      Because of my age I sometimes don’t get taking so seriously (well ok, I just made a tutorial with a bunny, so I can understand), yet I want to deal with the client as a professional. It is also sometimes a surprise if the client wasn’t aware of my age.

      And last, but definitely not least: I have so many more obligations. I’m still taking classes at high school, everyday I arrive at 4 ‘o clock in the afternoon, and only then can I start working on jobs (and I haven’t even started about homework).

      ( Reply )
      1. PG

        Andres November 6th

        I should add that, with the age, and besides authority, you also get more tired, more worried, and a lot more of work and obligations.

        man you just wait to apply to college… I’m 18 and I’m actually studying two careers at same time (interaction design and electronic engineering) and also I have a job as freelancer, job in a pro-design organization and also I work in college. That means that I have zero social life: no party, no rest, no tripping, no lover.

        But seriously, it’s not big deal. Daniel, I loved the tutorial it’s just what I needed to make a project I’m developing right now. Your rock men

  6. PG

    flora October 9th

    17 years wow!! ;)

    ( Reply )
  7. PG

    Todd October 9th

    nice to see this….i have been waiting forever for someone to explain tween classes…thx!

    ( Reply )
  8. PG

    Javier October 9th

    Very good tut. I would also like to add that the tweener class is very userful when creating custom Flex effects.

    One of the weakness though is you can’t tween colors, and you have to make your own color interpolator.

    ( Reply )
  9. PG

    Dario Gutierrez October 14th

    Great tut! Very well explained!

    ( Reply )
  10. PG

    VQ October 15th

    Nice tutorial! And you used my bunny (http://www.clickpopmedia.com/2008/03/25/spring-vectors-and-contest/)! Hooray!

    ( Reply )
    1. PG

      Daniel Apt October 15th

      Yes, and I must say, it’s awesome, so thank you!

      ( Reply )
  11. PG

    Polprav October 15th

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

    ( Reply )
    1. PG

      Daniel Apt October 16th

      Yeah you can, just mention the article and post a link. Do not copy and paste any contents of this article on your own blog.

      ( Reply )
    2. PG

      Daniel Apt October 16th

      Just read the Copyright & Usage (it’s in the footer):

      The effects and techniques demonstrated in tutorials on the Tuts network can be used in whatever manner you wish without attribution.

      The text, images and tutorials themselves are copyright their respective owners.

      You cannot copy whole tutorials, either in English or translated to another language.

      ( Reply )
  12. PG

    Neldo October 23rd

    try this:
    blog.greensock.com

    very powerfull and easy!

    ( Reply )
  13. PG

    azone December 13th

    very good tutorial,thank you!

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    December 13th