17 January 2011
General experience with programming in ActionScript 3 is suggested.
Beginning
The Timeline in Adobe Flash Professional presents a visual means of creating animation, but it is not the only means by which you can create animations. Programmatic animations offer more nuanced control. For example, you can create animations based on user interaction that are impossible to do with tweens created in the authoring environment.
The next sections describe the most popular and useful ways to use ActionScript to create animations, including animating with frame events, animating with the Tween class, animating with Motion XML, and sequencing animations
Even when nothing exists on the timeline, a SWF file will dispatch an Event.ENTER_FRAME event for any display object on the stage, once for every frame that passes. The frequency of this event depends upon the frame rate of the SWF file and the rendering speed of the client. You can create a function that modifies objects on the stage every time this event occurs to create animation. It is important to consider the performance impact of any callback function that listens to the Event.ENTER_FRAME event since this event is dispatched for every frame that a display object progresses through. Executing an excessive amount of instructions may slow down the rendering speed of the SWF file.
You can use the frame event to create games in ActionScript, even in just a few lines of code. The following example creates a simple version of a popular game where a paddle is used to redirect a ball toward a grid of bricks. Each time a frame passes, the updateBall() function is called, which determines if the ball has collided with the paddle or brick, reached the bounds of the stage, or needs to be reset after passing beyond the user's paddle.
Example
var bumper:Sprite = new Sprite();
bumper.graphics.beginFill(0xFF0000);
bumper.graphics.drawRect(0,0,100,10);
bumper.graphics.endFill();
bumper.x = 10;
bumper.y = stage.stageHeight - 20;
addChild(bumper);
var deltaX:Number = 5;
var deltaY:Number = 5;
var isBallActive:Boolean = false;
var ballStartX:uint = 100;
var ballStartY:uint = 200;
var ballRadius:uint = 6;
var ball:Sprite = new Sprite();
ball.graphics.beginFill(0);
ball.graphics.drawCircle(0,0,ballRadius);
ball.graphics.endFill();
ball.x = ballStartX;
ball.y = ballStartY;
addChild(ball);
Mouse.hide();
stage.frameRate = 31;
stage.addEventListener(MouseEvent.CLICK,startBall);
stage.addEventListener(MouseEvent.MOUSE_MOVE,moveBumper);
var bricks:Array = [];
function startBall(e:MouseEvent):void {
stage.addEventListener(Event.ENTER_FRAME,updateBall);
stage.removeEventListener(MouseEvent.CLICK,startBall);
}
function setupBricks():void {
var rows:uint = 5;
var cols:uint = 10;
var brickWidth:uint = 30;
var brickHeight:uint = 10;
var startX:Number = (stage.stageWidth - cols*(brickWidth+padding))/2;
var startY:Number = 10;
var padding:uint = 3;
var i:uint;
var j:uint;
for(i=0; i < rows; i++) {
for(j=0; j< cols; j++) {
var brick:Sprite = new Sprite();
var gradientMatrix:Matrix = new Matrix();
gradientMatrix.createGradientBox(brickWidth, brickHeight, Math.PI/2);
brick.graphics.beginGradientFill(GradientType.LINEAR,[ 0xFF0000, 0x990000 ],[1,1],[0,255],gradientMatrix);
brick.graphics.drawRect(0,0,brickWidth,brickHeight);
brick.graphics.endFill();
brick.x = startX + (j*(brickWidth+padding));
brick.y = startY + (i*(brickHeight+padding));
addChild(brick);
bricks.push(brick);
}
}
}
function moveBumper(e:MouseEvent):void {
bumper.x = e.stageX - bumper.width;
}
function updateBall(e:Event):void {
if(bumper.hitTestObject(ball)) {
var bumperCenterPoint:Number = bumper.x + (bumper.width/2);
deltaX = (ball.x - bumperCenterPoint)/2;
deltaY *= -1;
}
var i:uint;
var totalBricks:uint = bricks.length;
for(i=0; i < totalBricks; i++) {
var brick:Sprite = bricks[i];
if(brick.hitTestObject(ball)) {
bricks.splice(i,1);
removeChild(brick);
deltaY *= -1;
break;
}
}
if(ball.y <= ballRadius/2) deltaY *= -1;
else if(ball.y >= stage.stageHeight - ballRadius/2) {
ball.x = ballStartX;
ball.y = ballStartY;
deltaX = 5;
deltaY = 5;
stage.removeEventListener(Event.ENTER_FRAME,updateBall);
stage.addEventListener(MouseEvent.CLICK,startBall);
}
if(ball.x <= ballRadius/2) deltaX *= -1;
else if(ball.x >= stage.stageWidth - ballRadius/2) deltaX *= -1;
ball.x += deltaX;
ball.y += deltaY;
}
setupBricks();
Result
To get the source files for this example, download Breakout.zip from the top of this page. The Flash Professional CS5 version of the FLA file is called Breakout_CS5.fla.
The fl.transitions package contains the Tween class, which you can use to create animations directly from ActionScript. Easing classes in the fl.transitions.easing package provide the ability to customize how the tween performs. For example, you can use the Back, Bounce, Elastic, None, Regular, and Strong classes, each of which include easing functions that animate a display object in a non-linear fashion, such as moving faster at the start than at the finish.
The following example uses the Strong.easeIn easing method to smoothly animate a group of circles nearby wherever the user clicks their mouse.
import fl.transitions.Tween;
import fl.transitions.easing.*;
var circles:Array = new Array();
for(var i:uint = 0; i < 15; i++) {
var circle:Sprite = new Sprite;
// create a fill of random color and random alpha transparency
circle.graphics.beginFill(Math.random()*0xFFFFFF, Math.random());
circle.graphics.drawCircle(0,0,10);
circle.graphics.endFill();
addChild(circle);
// add each circle to an array for reference later in the tweenCircles function
circles.push(circle);
}
stage.frameRate = 31;
stage.addEventListener(MouseEvent.CLICK,tweenCircles);
function tweenCircles(e:MouseEvent):void {
// get each circle
for each(var circle:Sprite in circles) {
// tween this circle from its current position towards the mouse event position, adding some random variance
var xTween:Tween = new Tween(circle, "x", Strong.easeOut, circle.x, e.stageX + (Math.random()*100)-50, 1, true);
var yTween:Tween = new Tween(circle, "y", Strong.easeOut, circle.y, e.stageY + (Math.random()*100)-50, 1, true);
}
}
Result
To get the source files for this example, download RandomlyMovingCircle.zip from the top of this page. The Flash Professional CS5 version of the FLA file is called TweeningCircles_CS5.fla.
Animating with Motion XML contains functions and classes that describe motion tweens using XML. You can write the XML manually or use the authoring tool to generate it. Flash Professional includes a Copy Motion as ActionScript 3.0 command that generates ActionScript containing Motion XML Elements which describe a motion tween on the Timeline. You can use this generated ActionScript to apply the animation to other display objects. Alternatively, you can script your own XML and use the fl.motion classes to apply the animation to a specified display object instance.
The following is an example of a Motion XML Element that the authoring tool generates:
<Motion duration="10" xmlns="fl.motion.*" xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
<source>
<Source frameRate="12" x="24.5" y="197.55" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="Symbol 1">
<dimensions>
<geom:Rectangle left="0" top="0" width="15" height="15"/>
</dimensions>
<transformationPoint>
<geom:Point x="0.5" y="0.5"/>
</transformationPoint>
</Source>
</source>
<Keyframe index="0">
<tweens>
<SimpleEase ease="0"/>
</tweens>
</Keyframe>
<Keyframe index="9" x="30">
<tweens>
<SimpleEase ease="0"/>
</tweens>
</Keyframe>
</Motion>
When you apply the Motion XML element to a display object, this code creates a tween in which the object's x position increases by 30 pixels over 10 frames.
Objects can be programmatically animated without using the Timeline or authoring tool by using Motion XML in combination with an instance of the Animator class, as the following example illustrates:
import fl.motion.*;
import fl.motion.easing.*;
var motionXML:XML =
<Motion>
<Keyframe index="0" x="0">
<color>
<Color alphaMultiplier="0.1"/>
</color>
<tweens>
<FunctionEase functionName="fl.motion.easing.Bounce.easeIn"/>
</tweens>
</Keyframe>
<Keyframe index="31" x="40">
<color>
<Color alphaMultiplier="1"/>
</color>
<tweens>
<FunctionEase functionName="fl.motion.easing.Bounce.easeOut"/>
</tweens>
</Keyframe>
<Keyframe index="61" x="0">
<color>
<Color alphaMultiplier="0.1"/>
</color>
</Keyframe>
</Motion>;
var animator:Animator = new Animator(motionXML,box);
animator.play();
This code makes a movie clip on the stage, with an instance name of box, tween both alpha and position properties and back again.
Programmatic animation also provides nuanced control of playback. Animations do not all need to start when code is executed; animations can change playback or even be dynamically created in callback functions that execute when events dispatch from either Animator instances or Tween instances. In this way, animations can be sequenced.
The previous example used an Animator instance and a Motion XML element to create an animation. The following example is functionally identical, but uses the Tween class and its events to animate an instance named box:
import fl.transitions.*;
import fl.transitions.easing.*;
stage.frameRate = 31;
var box:Sprite = new Sprite();
box.graphics.beginFill(0xFF0000);
box.graphics.drawRect(0,0,25,25);
box.graphics.endFill();
box.x = 10;
box.y = 50;
addChild(box);
var myPositionTween:Tween;
var myAlphaTween:Tween;
setInitialTween();
function setInitialTween(e:TweenEvent = null):void {
myAlphaTween = new Tween(box, "alpha", Bounce.easeIn, 0.1, 1, 30, false);
myPositionTween = new Tween(box, "x", Bounce.easeIn, 10, 50, 30, false);
myPositionTween.addEventListener(TweenEvent.MOTION_FINISH,setReturnTween);
}
function setReturnTween(e:TweenEvent):void {
myAlphaTween = new Tween(box, "alpha", Bounce.easeIn, 1, 0.1, 30, false);
myPositionTween = new Tween(box, "x", Bounce.easeOut, 50, 10, 30, false);
myPositionTween.addEventListener(TweenEvent.MOTION_FINISH,setInitialTween);
}
The TweenEvent.MOTION_FINISH event occurs when a tween completes. By creating a tween in the callback function and adding a listener to this event, a loop is created and the tweens repeat indefinitely.
Note: Consider variable scope when using the Tween class. If a tween is created in a function, it is important that the variable's scope exists beyond the function itself. If a tween is stored to a variable of local scope, ActionScript garbage collection removes the tween as the function completes, which will likely be before the tween has even begun.
The following example creates a circle that moves to a random position every half second by creating a callback function that calls itself when the tween completes:
import fl.transitions.*;
import fl.transitions.easing.*;
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFF0000);
circle.graphics.drawCircle(0,0,40);
circle.graphics.endFill();
addChild(circle);
var xTween:Tween;
var yTween:Tween;
startTween();
function startTween(e:TweenEvent = null):void {
xTween = new Tween(circle, "x", None.easeNone, circle.x, Math.random()*500, 0.5, true);
yTween = new Tween(circle, "y", None.easeNone, circle.y, Math.random()*350, 0.5, true);
xTween.addEventListener(TweenEvent.MOTION_FINISH,startTween);
}
Result
To get the source files for this example, download TweeningCircles.zip from the top of this page. The Flash Professional CS5 version of the FLA file is called RandomlyMovingCircle_CS5.fla.
Related Flash Quick Starts