Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite 6
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions
  • Government

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection / Flash Developer Center /

Animating with ActionScript 3

by Buck DeFore

Buck DeFore

Content

  • Animating with frame events
  • Animating with the Tween class
  • Animating with Motion XML
  • Sequencing animations

Modified

17 January 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScriptanimationFlash Professional CC
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

General experience with programming in ActionScript 3 is suggested.

User level

Beginning

Required products

  • Flash Professional CC (Download trial)

Sample files

  • Breakout.zip (13 KB)
  • RandomlyMovingCircle.zip (13 KB)
  • TweeningCircles.zip (13 KB)

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

Animating with frame events

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 &lt; 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

This content requires Flash To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player. To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player.

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.

Animating with the Tween class

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 &lt; 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

This content requires Flash To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player. To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player.

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

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.

Sequencing animations

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

This content requires Flash To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player. To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player.

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

  • Making accessible user interfaces
  • Using ActionScript 3 drawing commands
  • Using color correction in Flash Player 10

More Like This

  • Displaying images with the TileList component
  • Loading images and Library assets with ActionScript 3
  • Filtering and formatting data in the DataGrid component
  • Event handling in ActionScript 3
  • Display list programming in ActionScript 3
  • Using the Label component
  • Getting started with Flash CS4 user interface components
  • Embedding fonts
  • Using ActionScript 3 drawing commands
  • Customizing and sorting the DataGrid component

Products

  • Adobe Creative Cloud
  • Creative Suite 6
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy (Updated) | Cookies

Ad Choices