Home Labs Galleries PetitOn

Using the Tween Class

In Flash MX 2004 and later, the developer has access to the ActonScript Tween class and the ease package, making it easy to do lots of fancy stuff. In this short tutorial we'll look at some image tweening.

To follow the tutorial you may want to download the project archive. It contains the fla and AS files, this tutorial and the image we will use in this experiment.

The Tween class and the easing package

The Tween class and the easing package are documented at ActionScript [org] and a brief and easily understood tutorial is given by Kirupa. The Tween class is used to change object parameters over time or over a frame interval.

The constructor of the Tween class is:

someTween = new mx.transitions.Tween( object, property, function,
			begin, end, duration, useSeconds )

It takes the following arguments:

object        The object to apply the tween to
property      The property to tween
function      The name of the easing class to use
begin         The start value of the property
end           The end value of the propety
duration      The duration in seconds or a frame interval
useSeconds    A boolean to tell if we want the duration
              to be in seconds ( default=true ) or frames

The Tween class uses easing functions to do the tweening in different ways.
The easing can be done in six ways or categories:

Strong
Back
Elastic
Regular
Bounce
None      No easing

It can be applied at different points in time ( frame interval )

easeIn        At the start
easeOut       At the end
easeInOut     At both start and end
easeNone      No easing. this goes with the None category

Tweening image transparency

In the first test of the Tween class we'll change the transparency of a JPEG image.


This is the image we are going to use

We start by creating a project directory and below that an images directory in which we save a suitable image for the experiment.

The Movie

In the Flash authoring tool ( I'm using Flash MX 2004 ) we create a new Flash Movie.

We then change the size of the Stage ( document size ) to fit the image, maybe adding a few pixels as a border and setting the background color..

The whole show will be run by an Actionscript application, so we don't have to create layers or a frame interval.

In the script pane for the first frame we add the following statements:

// The AlphaTween.as Actionscript will run the show.
#include "AlphaTween.as"
// and call its main function
main();

The script includes the ( so far non existing ) ActionScript AlphaTween.as, and calls its main() function, which will be our entry point to the AS application.

Before you save the project, make sure the publishing settings is for ActionScript 2.0
That's all for the fla file, and we save it as alphatween.fla.

The ActionScript

We are now going to write the ActionScript application AlphaTween.as, using any plain text editor.
I am using TextPad because I think it's a good programmers editor, and it can save the text as Unicode, with the character encoding UTF-8.
Save the text file in the same directory as the fla file and start coding..

We start by importing the classes we will use

import mx.transitions.Tween;
import mx.transitions.easing.*;

The first import statement imports the Tween class, which is found in the mx.transitions package. The second imports the whole easing package.

We need some global variables to hold values that should be accessible from our functions.

// Global variables
var mc:MovieClip;    // The container for the image
var alphaStart = 20; // Start with an alpha value of 20%

Here is the entry point to the application

function main(){
	getImage();
}

The main function is there only to get a well defined entry point, in case we want to do something more later. Here it merely calls the getImage function.

function getImage(){
	// Create a new MovieClip attached to _root
	mc = _root.createEmptyMovieClip( "photo", i );

	// position the clip
	mc._x = 1;
	mc._y = 1;

	// create a movieclip so that our onPress isn't
	// overwritten by the jpg
	mc.createEmptyMovieClip( "jpgHolder", 1 );

	// and load the jpeg into it
	mc.jpgHolder.loadMovie( "images/petit.jpg" );

	// Default start value for alpha
	mc._alpha = alphaStart;

	// add the onPress handler to the movieclip
	mc.onPress = doTween;
}

The getImage() function creates a new empty MovieClip and attaches it to the _root, i.e. the upper most node of the movie.

The MovieClip will be accessible via the variable mc.

The size of the Stage is 2 pixels higher and wider than the image, so I'll place the clip at [ 1,1 ], upper left corner.

We want the user to start the metamorphoses, by clicking the image, so we attach an event handler to the clip. The problem with this is that when we load the image, such an event handler will be orverwritten.

The solution is simple though. We just create another MoviClip, "jpgHolder" within the first one to load the image.

We also set the alpha value for the clip to start with. Then we load the image using the loadMovie function of the jpgHolder, passing along the URL or path of the image.

Finally we add an onPress event handler to the outer MovieClip mc. the actual event handling is delegated to an doTween function.

// Do the alpha tween on the MovieClip
function doTween(){
	var mcTween:Tween = new Tween( mc, "_alpha", Strong.easeOut, 20, 100, 5, true );
};

The tween is done as soon as we have created a new instance of the Tween class. The new Tween instance is held by the variable mcTween, in case we want to call other functions on it.

The constructor is called when we create the instance using new, and the arguments decides what should be done.

Here we pass the MovieClip mc, and the _alpha property we want to affect. We say that the easing should be Strong and be active at the end of the change.

The alpha value should start at 20% and go to 100% over 5 seconds.

Here is the complete AlphaTween.as

Now we can save the ActionScript and run the movie from Flash MX.
When everything works, we can publish the Movie to SWF and possibly embedded in HTML.

Click on the image to start/restart the tweening!

Tweening Image Size

In the second tweening demonstration, let's change the size of the image over a short period of time.

A MovieClip has no _scale property, but _xscale and _yscale properties, so we have to do two simultaneous tweenings.

We make a new Flash Movie called scaletween.fla and include a new AS application called ScaleTween.as

The MovieClip setup and the image loading will be the same.
The only thing that will change in our code, is the doTween function and we'll use other global variables.

// Global variables
var mc:MovieClip; // The container for the image
var scaleTo = 40; // We will scale the image to 40%

Here is the new tweening function invoked by our event handler

// Do the scaling tween on the MovieClip
function doTween(){
      var mcXScale:Tween = 
              new Tween( mc, "_xscale", Regular.easeIn, 100, scaleTo, 3, true );
      var mcYScale:Tween = 
              new Tween( mc, "_yscale", Regular.easeIn, 100, scaleTo, 3, true );
};

Simple as that!

We just create two Tween instances and pass the tweening parameters as arguments to the constructor. The instances will work in parallell. We don't have to use the same easing type or the same duration, but we do here to get a conform scaling on both axes.

Here is the complete ScaleTween.as

Click on the image to start/restart the tweening!

Combining Tweens on Different Properties

As you have no doubt already guessed, it is possible to combine tweens on different properties. Well, we have seen that: the _xscale and _yscale are different properties of our MoviClip. The new Flash Movie is combotween.fla, and the new ActionScript application is ComboTween.as.

So without further ado, here are the new globals and the tweening function.

// Global variables
var mc:MovieClip; 	// The container for the image
var scaleFrom = 40;	// Start with a scale value of 40%
var alphaStart = 20;	// Start with an alpha value of 20%
function doTween(){
	var mcXScale:Tween =
		new Tween( mc, "_xscale",
		Regular.easeIn, scaleFrom,  100, 2, true );

	var mcYScale:Tween =
		new Tween( mc, "_yscale",
		Regular.easeIn, scaleFrom,  100, 2, true );

	var mcAlpha:Tween =
		new Tween( mc, "_alpha" ,
		Strong.easeIn,  alphaStart, 100, 2, true );
};

That wasn't hard, was it? Let's do something else!

The End of Tween Event

Almost any distinct event in Flash, such as entering a frame, clicking the mouse or loading an image, is associated with an event handler and the firing of an event object.

Event handlers, such as onPress and onMouseMove and onEnterFrame are properties of an instance of MovieClip.

When the tweening comes to an end, there is an onMotionFinished event which we can use to do something, when the tweening finishes.

According to ActionScript [org] documentation, we can use the following construct to catch this event.

plsTween.onMotionFinished = function() {
	// Do something here
};

However this throws an error, and after some searching for this event handler I found the following explanation in a comment at Macromedia Livedocs:

"In the Tween class in Flash MX 2004 the onMotionFinished is not
declared as an instance property. Therefore the sample script should
yield an compile error. To avoid this error (1) the Tween instance should
be typed as Object, or (2) the onMotionFinished event handler method
should be set with the bracket ([]) access instead of with the dot (.)
access.
"

(1) var myTween:Object = new Tween (arguments);
(2) myTween["onMotionFinished"] = function () {statement(s)}"

So lets try this to rewind the tweening once it's finished. The doTween function will look like this.

// Do the combination tween on the MovieClip
function doTween(){
	var mcXScale:Tween =
		new Tween( mc, "_xscale",
		Regular.easeIn, scaleFrom,  100, 2, true );

	var mcYScale:Tween =
		new Tween( mc, "_yscale",
		Regular.easeIn, scaleFrom,  100, 2, true );

	var mcAlpha:Tween =
		new Tween( mc, "_alpha" ,
		Strong.easeIn,  alphaStart, 100, 2, true );

	// A finished tween event handler
	mcAlpha["onMotionFinished"] = function(){
		mcXScale.rewind();
		mcYScale.rewind();
		mcAlpha.rewind();
	}
};

Here is the completed ComboTween.as

Click the image to see the combined tweening!

There is naturally a lot more that can be done with the classes in the mx.transition packages, but this was hopefully a teaser.

Explore and experiment and have fun!