10 May 2010
This article assumes you have a basic understanding of the Flash Professional authoring environment and some previous experience writing ActionScript.
Intermediate
The Adobe ActionScript 3 language offers programmatic access to most of the elements in Adobe Flash Player. Included in the ActionScript language are several classes devoted to creating animation, which allow you to create simple or complex motion effects without using a timeline.
This article shows you how easy it is to use the ActionScript 3 animation features in Adobe Flash Professional CS5, even if don't regularly use ActionScript. You'll explore the range of options available and learn how to animate movie clips and components to add animation to your SWF applications.
New to Flash Professional CS5 is the ability to automate coding tasks using the Code Snippets panel (see Figure 1). Code snippets are collections of commonly used code blocks which you can use to add functionality to your Flash movie. Included in the mix are a range of options related to animation.
If you're new to writing ActionScript, the snippets are a great way to become familiar with the ActionScript syntax. If you're already up and running with your ActionScript skills, you'll be able to speed up repetitive coding tasks by creating your own custom snippets.
The general workflow while using code snippets includes selecting an instance or a keyframe on the Timeline and then adding a code snippet by clicking the snippet name in the Code Snippets panel. The command generates an Actions layer and assigns code to it on the Timeline (in ActionScript 3, code must be placed on a timeline). If an instance is selected before running the command, the instance name is automatically inserted in the new code. Most often you'll click the keyframe containing the script and edit the code in the Actions panel.
The code snippets are divided into six groups:
Take a moment to explore the options available in the six categories.
The following example demonstrates how to use a code snippet to enable keyboard control over a graphic:
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.
Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_PressKeyToMove);
function fl_PressKeyToMove(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
image_mc.y -= 5;
break;
}
case Keyboard.DOWN:
{
image_mc.y += 5;
break;
}
case Keyboard.LEFT:
{
image_mc.x -= 5;
break;
}
case Keyboard.RIGHT:
{
image_mc.x += 5;
break;
}
}
}
The Code Snippet panel is a handy place to create a library of code-driven animation effects. You can experiment with the supplied snippets code or create endless effect variations using your own code. The following example demonstrates how to save a simple tween effect as a reusable code snippet.
Follow these steps to create a custom snippet:
import fl.transitions.*;
import fl.transitions.easing.*;
/**
* This Tween sample shows a fade-in effect
* by default. Change the prop, to, from, and duration
* values to change the animation. You can add code
* in the event handler functions to respond to animation
* event timing.
*/
function onTweenProgress(event:TweenEvent):void
{
// do something as the tween progresses...
}
function onTweenEnd(event:TweenEvent):void
{
// do something when the tween ends...
}
var prop:String = “alpha”;
var from:Number = 0;
var to:Number = 1;
var duration:Number = 1;
var tween:Tween = new Tween(instance_name_here, prop, Strong.easeOut, from, to, duration, true);
tween.addEventListener(TweenEvent.MOTION_CHANGE, onTweenProgress);
tween.addEventListener(TweenEvent.MOTION_FINISH, onTweenEnd);
Follow these steps to apply the custom snippet:
prop, from, to, and duration variables to change the animation. Try the following settings:You'll dive into the details of working with the Tween class in the next section. As you explore the samples in the following pages, try to think of how you might build your snippet library.
Read more about the Code Snippets panel in the Add interactivity with code snippets section of the Flash CS5 Help documentation. Also see Yuki Shimizu's article, Code snippets for beginning ActionScript 3 programmers and designers, in the Flash Developer Center.
Prebuilt classes in ActionScript provide a way to access various types of features and objects within the SWF application. The Tween, TransitionManager, and easing classes provide a simple way to add animations and transitions dynamically to your movie. The process for using these classes is very similar to the ActionScript 2 versions. The main difference between the ActionScript 2 and the ActionScript 3 classes is that the ActionScript package is now "fl" instead of "mx" as it appeared previously.
This section provides an overview of the tween, transition, and easing options available in ActionScript 3. You'll start by looking at the basics of code-generated tweening.
Note: The Tween and TransitionManager classes also exist in the ActionScript 2 language in the "mx" component package. For more information, read About the Tween and TransitionManager classes in the ActionScript 2 documentation.
If you're working with the Tween or transition classes, you'll start your code off by importing the transitions package (as well as the easing package if you're planning on using easing). Add this code to the top of the Script window in the Actions panel:
import fl.transitions.*;
import fl.transitions.easing.*;
An ActionScript package is a group of ActionScript classes that are related. By importing the transitions and easing packages at the start of your script, you can access the objects within the package directly by their class name to save horizontal space. Importing the class also instructs Flash Professional CS5 to compile the classes along with the SWF file.
Tip: In Flash Professional CS5, import statements are generated automatically when you data type your variables in the Actions panel. To use this feature, declare your variable using the var keyword and the name of the variable followed by a space and a colon. Typing in the space and colon after the variable name triggers the code hint menu and automatic addition of the import statement at the top of the script.
Transitions are animations that can be applied to movie clips to make them transition "in" or "out" of the screen. ActionScript 3 includes 10 different transition classes, which you can customize using the easing methods, and several optional parameters.
Flash Professional CS5 includes the following transitions for use with the TransitionManager class:
Each transition has slightly different customizations that you can apply to the animation. The TransitionManager class is the manager object that you use to interact with the transitions.
The following code shows how to create a Wipe transition:
import fl.transitions.*;
import fl.transitions.easing.*;
// Apply wipe transition
TransitionManager.start(img1_mc, {type:Wipe, direction:Transition.IN, duration:2, easing:None.easeNone, startPoint:1});
The code above assumes that there is a movie clip instance named "img1_mc" on the Stage. These few lines of code are all that is needed to create a wipe effect in your movie.
Notice that you pass in the instance of the target and an object containing transition parameters. The parameters always include the type, direction, duration, and easing properties—along with any other transition specific properties required.
See the TransitionManager class section of the ActionScript 3 Language Reference for more information.
Easing refers to gradual acceleration or deceleration during an animation. For example, a ball might gradually increase its speed near the beginning of an animation, but slow down right at the end of the animation before it arrives at a full stop. Adding easing helps your animations appear more realistic.
Flash offers six easing classes for use with the Tween and TransitionManager classes:
The previous six easing classes each have three easing methods:
Note: The None class contains the easeNone method, as seen in the TransitionManager code example above.
If you want to open these classes in Flash or read the code in your ActionScript editor, you can find the class files in Adobe\Adobe Flash CS5\Common\Configuration\ActionScript 3\projects\Flash\src\fl\transitions.
See the fl.transitions.easing package section of the ActionScript 3 Language Reference for more information on the TransitionManager class.
The Tween class enables you to move, resize, and fade movie clips easily on the Stage, similar to a tween built along the Timeline.
For example, imagine that you want to move a movie clip across the Stage. Your options would include:
onEnterFrame event handler to power the animationOne of the easiest ways to create a tweened animation is to use the Tween class. Use the following ActionScript:
import fl.transitions.*;
import fl.transitions.easing.*;
var myTween:Tween = new Tween(ball_mc, "x", Elastic.easeOut, 0, 300, 3, true);
The previous ActionScript code example creates a new instance of the Tween class, which animates the ball_mc movie clip on the Stage along the x axis (left to right). The movie clip animates from 0 pixels to 300 pixels in three seconds, and the ActionScript applies an elastic easing method. This means the ball extends past 300pixels on the x axis before animating back using a fluid motion effect.
The following list shows the parameters in the Tween constructor:
Tween(obj, prop, func, begin, finish, duration, useSeconds)
infinity if the value is negative or omittedThe first code example above demonstrates the settings to use to set the duration of the animation in seconds. Instead of using seconds, you can fade the symbol over a few frames. To set the duration in frames instead of seconds in the Tween class, you change the final parameter, useSeconds, from true to false. When you set the parameter to true, you tell Flash that the specified duration is measured in seconds. Or, if you set the parameter to false, the duration is the number of frames you want to use for the tween. For example, let's examine the following code:
import fl.transitions.Tween;
import fl.transitions.easing.*;
var myTween:Tween = new Tween(ball_mc, "alpha", Strong.easeIn, 1, 0, 24, false);
The previous code example fades out the ball_mc instance using the Strong.easeIn easing method. Instead of fading the instance for three seconds, it fades the instance across 24 frames. Using frames instead of seconds offers you a lot more flexibility, but remember that the duration is tied to the frame rate of the current Flash document. If your Flash document uses a frame rate of 12 frames per second (fps), then the previous code snippet fades the instance over two seconds (24 frames/12 fps = 2 seconds). However, if your frame rate is 24 fps, then the same code fades the instance over one second (24 frames/24 fps = 1 second). If you use frames to measure duration, you can significantly change the speed of your animation when you change the document's frame rate, without modifying your ActionScript.
The standard frame rate for a Flash movie is 24 frames per second (same as the standard motion-picture rate). This standard frame rate produces the best results on the web. Note that the complexity of your animation (overlapping graphics, transparencies, blends and effects, etc.) along with the speed of the computer viewing the movie will affect the smoothness of the playback.
Read about the Tween class in the ActionScript 3 Language Reference for more information.
You can use the transition and Tween classes to add animations to movie clips and components using ActionScript. Doing so allows you to easily experiment with graphic transformations and different types of easing effects. While you can create these types of effects from scratch using ActionScript, the code and mathematics can quickly become complex. Using the prebuilt classes can save a lot of time and energy.
To use the transition class to animate a movie clip zooming in on the Stage, follow these steps:
import fl.transitions.*;
import fl.transitions.easing.*;
TransitionManager.start(img1_mc, {type:Zoom, direction:0, duration:3, easing: Bounce.easeOut});
duration (in the previous code example) from one second to two or three seconds.You might notice that the image anchors in the upper-left corner, and it grows towards the lower-right corner. If you want images to zoom in from the center, instead of anchoring on a corner, you'll need to modify the symbol's registration point when you convert the image from a bitmap (see Step 2 above). Follow these steps:
import fl.transitions.*;
import fl.transitions.easing.*;
TransitionManager.start(img2_mc, {type:Zoom, direction:0, duration:3, easing: Bounce.easeOut});
If you modified the duration in Step 7 above, modify this code example to the use the same number.
As you can see, creating complex animations is extremely easy using transitions, and doesn't require you to create motion or shape tweens on the Timeline. And most importantly, you don't need to use complex math calculations to create easing methods.
Note: Some transitions are sensitive to where you locate the registration point in the movie clip. Changing the registration point can have a dramatic effect on how the animation looks in an SWF file.
To use the Tween class to animate an object, follow these steps:
import fl.transitions.*;
import fl.transitions.easing.*;
function finishHandler(event:TweenEvent):void
{
// Place your actions here
trace("MOTION_FINISH time = "+event.time);
}
var myTween:Tween = new Tween(img1_mc, "y", Elastic.easeOut, 0, 250, 3, true);
myTween.addEventListener(TweenEvent.MOTION_FINISH, finishHandler);
Note: This code example shows how to create a simple tween with an event handler function assigned to "listen" to the animation. Events are timing hooks that allow you to respond to various points in the animation. You can respond to the following events: motionChange, motionFinish, motionLoop, motionResume, motionStart, and motionStop.
img1_mc finishes animating on the Stage.Read about the Tween class in the ActionScript 3 Language Reference for more information.
What if you want to move the ball after the initial animation completes? There are at least two ways you can handle this. The first, and perhaps the most obvious solution, is to re-animate the ball using the motionFinished event. While this solution works, the Tween class offers a simpler solution: the continueTo() method. The continueTo() method instructs the tweened animation to continue from its current value to a new value. You can see how this works in the following ActionScript:
import fl.transitions.*;
import fl.transitions.easing.*;
var ball_tween:Object = new Tween(ball_mc, "x", Regular.easeIn, 0, 300, 3, true);
function handleFinish(event:TweenEvent):void {
ball_tween.continueTo(0, 3);
};
ball_tween.addEventListener(TweenEvent.MOTION_FINISH, handleFinish);
After the initial tween finishes, the ball_mc movie clip tweens back to its original position at 0 pixels (assuming that the symbol's registration point is located on the left side of the graphic).
There are only two arguments that pass to the continueTo() method, instead of the seven arguments for the Tween method. The five missing arguments (obj, prop, func, begin, and useSeconds) in the continueTo() method use the arguments that you defined earlier in the call to the Tween class. When you call the continueTo() method, you assume the obj, prop, func (easing type), and useSeconds arguments are the same as in the earlier call to the Tween class. The continueTo() method uses the finish value from the call to the Tween class, instead of specifying a value for the begin argument.
You can even make an animation continue animating back and forth along the x axis without stopping. The Tween class also accommodates this kind of animation with the aptly named yoyo() method. The yoyo() method waits for the motionFinished event to execute, and then it reverses the begin and finish parameters. The animation begins again, as demonstrated in the following example.
import fl.transitions.*;
import fl.transitions.easing.*;
var box_tween:Tween = new Tween(box_mc, "x", Regular.easeInOut, 0, stage.stageWidth, 3, true);
function handleFinish(event:TweenEvent):void {
box_tween.yoyo();
}
box_tween.addEventListener(TweenEvent.MOTION_FINISH, handleFinish);
box_mc movie clip. You can see how this is accomplished in the following revised code from Step 8:import fl.transitions.*;
import fl.transitions.easing.*;
var box_tween:Tween = new Tween(box_mc, "x", Regular.easeInOut, 0, stage.stageWidth - box_mc.width, 3, true);
function handleFinish(event:TweenEvent):void {
box_tween.yoyo();
}
box_tween.addEventListener(TweenEvent.MOTION_FINISH, handleFinish);
Now test the animation, and notice how the box stops easing before it exits the boundaries of the Stage.
One of the new features available in Flash Player 10 is the ability to animate two-dimensional objects in three-dimensional space (see Figure 8). New tools in the authortime environment and new properties in the DisplayObject class and geom package allow for projecting objects into perspective.
The rotation effect seen in Figure 5 can be achieved in ActionScript using the new properties of the DisplayObject class. All sprites and movie clips are display objects in ActionScript 3. You're probably familiar with using the x and y property of the MovieClip object in older versions of the language. In Flash Professional CS5, the x and y properties are joined by the z property, representingdepth.
Note: 3D tools were first added to Flash CS4 Professional for Flash Player 10 and later.
Movie clips and sprites have access to the following transformational properties:
xyzrotationrotationXrotationYrotationZscaleXscaleYscaleZtransformNotice that the rotation property has been split into three separate properties in addition to the transitional rotation property. The transform property accepts a 3D matrix for more advanced multi-property transformations.
As you can see, the updates come in the form of the new z properties. The z property deals with distance from a point of view. An object whose z property is 100 is further away from your viewpoint than an object whose z property is 50. As seen in Figure 8, if the z coordinates of the top of the rectangle are greater than the z coordinates of the bottom of the rectangle, the shape appears to lean back, creating a rotational effect. Using the rotation properties, you can easily create these types of effects on your two-dimensional graphics.
It's easy to use the rotation properties to create some interesting animation effects. The following example uses an enterFrame event to generate the continuous animation of a two-dimensional object in three-dimensional space:
function enterFrameHandler(event:Event):void
{
sq_mc.rotationY += 5;
}
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
rotationY value to a rotationZ value:function enterFrameHandler(event:Event):void
{
sq_mc.rotationZ += 5;
}
addEventListener(Event.ENTER_FRAME,
enterFrameHandler);
rotationX and rotationZ property to see the z axis appear in perspective:function enterFrameHandler(event:Event):void
{
sq_mc.rotationY += 5;
sq_mc.rotationZ += 5;
}
addEventListener(Event.ENTER_FRAME,
enterFrameHandler);
Note: The ENTER_FRAME event is a part of all sprites and movie clips. When an enterFrame event handler is added to the timeline of either of these types of objects, the related event handler function is called every time a frame is entered. For sprites and movie clips containing a single frame, the event handler is called repeatedly at an interval matching the frame rate.
Often you’ll want to clear the 3D rotation effects applied to an object after the animation ends. In some cases a slight distortion or blur may appear on the graphic. By clearing the matrix3D property you can return the graphic to its original state.
The following example demonstrates how to clear a 3D transformation on an object that rotates a full 360 degrees:
import fl.transitions.*;
import fl.transitions.easing.*;
import flash.geom.Point;
function onTweenFinish(event:TweenEvent):void
{
// Clear the 3D effect and
// resume original position...
sq_mc.transform.matrix3D = null;
sq_mc.x = pt.x;
sq_mc.y = pt.y;
}
var pt:Point = new Point(sq_mc.x, sq_mc.y);
var tween:Tween = new Tween(sq_mc,"rotationX",Bounce.easeOut,0,360,1.5,true);
tween.addEventListener(TweenEvent.MOTION_FINISH, onTweenFinish);
Notice the three lines of code in the onTweenFinish event handler function. The first line clears the matrix3D property followed by repositioning the object to its original point on the screen.
Updates to the geom package in ActionScript 3 include a number of classes devoted to working with 3D transformations:
The Matrix3D class allows you to perform transformations to all three axes at the same time, which can yield greater performance and code efficiency. The PerspectiveProjection class provides an easy way to apply a 3D transformation to an object or view without explicitly building a Matrix3D instance. The Orientation3D class, Utils3D class, and Vector3D class provide supporting utilities and objects to aid in creating the transformation.
It's easy to use the rotation properties to create some interesting animation effects. The following example uses an ENTER_FRAME loop to generate the continuous animation of a two-dimensional object in three-dimensional space:
// Set position in the z axis
square1.z = 200;
square2.z = 500;
// Flag while dragging circle
var isDragging:Boolean = false;
// Change the projection center in relation to the
// circle while it's being dragged...
function dragPressHandler(event:Event)
{
isDragging = true;
focalPt.startDrag();
}
function dragMoveHandler(event:Event)
{
if( isDragging ){
root.transform.perspectiveProjection.projectionCenter = new Point(focalPt.x, focalPt.y);
}
}
function dragReleaseHandler(e:Event)
{
focalPt.stopDrag();
isDragging = false;
root.transform.perspectiveProjection.projectionCenter = new Point(focalPt.x, focalPt.y);
}
focalPt.addEventListener(MouseEvent.MOUSE_DOWN, dragPressHandler);
focalPt.addEventListener(MouseEvent.MOUSE_MOVE, dragMoveHandler);
focalPt.addEventListener(MouseEvent.MOUSE_UP, dragReleaseHandler);
Notice that the first thing the script does is place the two-square back in space (z axis) in relation to the focalPt instance, which has no adjustment to its z axis.
Read about the PerspectiveProjection class in the ActionScript 3 Language Reference for more information.
Another cool animation feature new to Flash Player 10 is the ability to create an armature using the Bone tool. An armature is a series of symbols or shapes that are linked so that they move in relation to each other when clicked on or animated. This method of animation is called inverse kinematics (IK). The classic example is a puppet on marionette strings. The puppet is made up of limbs bound together at the joints. When the puppeteer moves any of the strings, the limbs connected to that joint move in relation to the limb that changed position.
Armatures add new visual states to the Flash authoring environment (see Figure 9). The lines that connect the center points of the objects are called bones. The joints at which the bones connect can be selected so that unique properties and constraints can be applied to each section of the armature.
Note: The Bone tool was first added to Flash CS4 Professional for Flash Player 10 and later.
The first thing to mention is that armatures cannot be dynamically created at runtime. They must be created at authortime using the Bone tool in Flash Professional. This is easy to do.
Once you've created an armature, you can save it in a movie clip and animate it using ActionScript at runtime. So in terms of programmatic animation, working with armatures is a two-step process where the first step involves building the armature in a FLA file in Flash.
Follow these steps to create an armature:
In this sample the animation actually happens as part of the behavior of the armature. When you publish the movie, you can click on the circles to see them move in relation to one another. To visualize the segments of the armature better, and to provide a foundation for some interesting animation possibilities, the following code addition will analyze the armature using ActionScript and draw lines between the joints.
Follow these steps to finish off the sample:
import fl.ik.*;
import flash.display.Sprite;
// Retrieve the armature and the root joint
var armInst:IKArmature = IKManager.getArmatureAt(0);
var rootJnt:IKJoint = armInst.rootJoint;
var lineContainer:Sprite = new Sprite();
// Add a container for drawing lines
// to the bottom of the display object stack
addChild(lineContainer);
setChildIndex(lineContainer, 0);
// Traverse the armature and draw lines to
// connect the joint...
function drawConnectingLines(jnt:IKJoint):void
{
var len:uint = jnt.numChildren;
for(var n:uint=0;
n<len; n++)
{
var childJnt:IKJoint = jnt.getChildAt(n);
var childClip1:DisplayObject = getChildByName(childJnt.bone.headJoint.name);
var childClip2:DisplayObject = getChildByName(childJnt.bone.tailJoint.name);
lineContainer.graphics.lineStyle(3, 0xCCCCCC);
lineContainer.graphics.moveTo(childClip1.x, childClip1.y);
lineContainer.graphics.lineTo(childClip2.x, childClip2.y);
drawConnectingLines(childJnt);
}
}
// Update line drawing every frame
function enterFrameHandler(event:Event):void
{
lineContainer.graphics.clear();
drawConnectingLines(rootJnt);
}
addEventListener(Event.ENTER_FRAME,
enterFrameHandler);
For more information about this feature, see Using inverse kinematics in the Flash CS5 Help documentation. Also be sure to read Chris Georgenes's article, Character animation with the Bone tool in Flash.
Another powerful animation feature related to ActionScript 3 is the ability to copy a timeline-based motion tween and paste it as ActionScript 3 code. This allows you to create dynamic, script-based animation controls for 2D or 3D effects—even if you're new to working with ActionScript.
You can copy the following properties of a motion tween:
The Copy Motion as ActionScript 3 command applies the copied tween properties as an ActionScript definition or an XML definition. While XML is an efficient way to describe a tween, by default Flash Professional applies property values as an array to the AnimatorFactory class.
The process for creating an animation using Copy Motion as ActionScript 3 is simple. You start by creating a tween visually along the Timeline, creating whatever effects you desire. By right-clicking the tweened instance, you can select the option to Copy Motion as ActionScript 3 or Copy Motion.
Tip: If you like your tween animation and would like to save it for reuse as a Motion Preset, you can right-click the instance and select the Save as Motion Preset option.
If you don't need to save the tween properties beyond your immediate edits, you can simply use the Copy Motion command to copy a tween and paste it elsewhere in your file or in a separate file.
In this demonstration you will use the Copy Motion command to generate a copy of the properties of a tween animation and apply them to an instance in a separate file.
To copy and paste a tween between objects:
If you would like to be able to reuse the code that generates the tween, you can use the Copy Motion as ActionScript 3 command.
In this demonstration you will use the Copy Motion as ActionScript 3 command to generate a copy of the properties of a tween animation and apply them to a separate file.
To create a reusable ActionScript 3 animation:
import fl.motion.AnimatorFactory;
import fl.motion.MotionBase;
import flash.filters.*;
import flash.geom.Point;
var __motion_shape_mc:MotionBase;
if(__motion_shape_mc == null) {
import fl.motion.Motion;
__motion_shape_mc = new Motion();
__motion_shape_mc.duration = 30;
// Call overrideTargetTransform to prevent the scale, skew,
// or rotation values from being made relative to the target
// object's original transform.
// __motion_shape_mc.overrideTargetTransform();
// The following calls to addPropertyArray assign data values
// for each tweened property. There is one value in the Array
// for every frame in the tween, or fewer if the last value
// remains the same for the rest of the frames.
__motion_shape_mc.addPropertyArray("x", [0,3.97311,8.40006,13.3186,18.7471,24.7331,31.3031,38.4825,46.2956,54.7578,63.8896,73.665,84.0945,95.1365,106.738,118.856,131.428,144.384,157.653,171.187,184.905,198.775,212.74,226.781,240.837,254.924,268.981,283.03,297.043,311]);
__motion_shape_mc.addPropertyArray("y", [0,13.5007,26.857,40.057,53.0306,65.7758,78.2331,90.3444,102.053,113.294,124.016,134.125,143.585,152.323,160.286,167.446,173.783,179.291,183.979,187.877,191.01,193.423,195.157,196.26,196.773,196.742,196.207,195.207,193.776,191.95]);
__motion_shape_mc.addPropertyArray("scaleX", [1.000000]);
__motion_shape_mc.addPropertyArray("scaleY", [1.000000]);
__motion_shape_mc.addPropertyArray("skewX", [0]);
__motion_shape_mc.addPropertyArray("skewY", [0]);
__motion_shape_mc.addPropertyArray("rotationConcat", [0,-4.13792,-8.27584,-12.4138,-16.5517,-20.6896,-24.8275,-28.9655,-33.1034,-37.2413,-41.3792,-45.5172,-49.6551,-53.793,-57.931,-62.0689,-66.2068,-70.3447,-74.4827,-78.6206,-82.7585,-86.8964,-91.0344,-95.1723,-99.3102,-103.448,-107.586,-111.724,-115.862,-120]);
__motion_shape_mc.addPropertyArray("blendMode", ["normal"]);
// Create an AnimatorFactory instance, which will manage
// targets for its corresponding Motion.
var __animFactory_shape_mc:AnimatorFactory = new AnimatorFactory(__motion_shape_mc);
// Call the addTarget function on the AnimatorFactory
// instance to target a DisplayObject with this Motion.
// The second parameter is the number of times the animation
// will play - the default value of 0 means it will loop.
// __animFactory_shape_mc.addTarget(<instance name goes here>, 0);
}
<instance name goes here> text with the name of the instance to be animated and update the 0 to the number of times you'd like the animation to loop:__animFactory_shape_mc.addTarget(shape_mc, 1);
If you would like to save the animation properties in Motion XML format, you can use the Copy Motion as XML command in the Commands menu.
In this demonstration you will use the Copy Motion as XML command to generate XML and code, and then apply them in a different file.
To create an ActionScript 3 Motion XML animation:
import fl.motion.Animator;
var my_tween_xml:XML =
import fl.motion.Animator;
var my_tween_xml:XML = <Motion duration="20" xmlns="fl.motion.*"
xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
<source>
<Source frameRate="30" x="80.45" y="83" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="tweenShape">
<dimensions>
<geom:Rectangle left="-35.45" top="-41" width="70.95" height="82"/>
</dimensions>
<transformationPoint>
<geom:Point x="0.4996476391825229" y="0.5"/>
</transformationPoint>
</Source>
</source>
<Keyframe index="0" tweenSnap="true" tweenSync="true">
<tweens>
<SimpleEase ease="0"/>
</tweens>
</Keyframe>
<Keyframe index="19" x="326" y="201.95" rotation="135"/>
</Motion>
var my_animator:Animator = new Animator(my_tween_xml, shape_mc);
my_animator.play();
Note: If you build your tween in a Flash CS3 ActionScript 3 FLA file, or use a classic tween, Flash will default to using Motion XML for the tween description.
To learn more about the motion XML format, read Motion XML Elements in the ActionScript 3 Language Reference.
The BitmapData class allows you to generate bitmap images dynamically in ActionScript. It's used most commonly to manipulate video or imported images but it can also be used to render graphics from scratch or from vector content.
While there are many uses for this powerful class, a common, day-to-day use is to take snapshots of items on the screen. The BitmapData class can take snapshots of vector (and bitmap) objects and paint them into a new image as a single bitmap. Beyond the ability to flatten groups of content, it's often desirable to work with bitmaps for large animations or screen transitions, since bitmaps do not have to be redrawn for every frame, as vectors do. This approach can greatly improve Flash Player performance.
Following these steps to create a transition using the BitmapData class:
import fl.transitions.*;
import fl.transitions.easing.*;
// Generate overlapping vector
// graphics in a Sprite container...
function createRectangle(x:Number, y:Number, w:Number, h:Number):void
{
var sprt:Sprite = new Sprite();
sprt.graphics.lineStyle(Math.random()*2, 0×000000);
sprt.graphics.beginFill(0×00FFCC);
sprt.graphics.drawRect(0, 0, w, h);
sprt.graphics.endFill();
sprt.x = x;
sprt.y = y;
imageContainer.addChild(sprt);
}
var imageContainer:Sprite = new Sprite();
addChild(imageContainer);
// Randomly build 200 of graphics
for(var n:Number=0;
n<200; n++)
{
var useX:Number = Math.random()* 400;
var useY:Number = Math.random()* 400;
var useW:Number = Math.random()* 400;
var useH:Number = Math.random()* 400;
createRectangle(useX, useY, useW, useH);
}
// Tween to fade out
var fadeOut:Tween = new
Tween(imageContainer, "alpha", Strong.easeOut, 1 , 0, 78);
// Take a snapshot of the imageContainer sprite
// so it can be animated as a single bitmap object
// during the transition
var fadeOutTarget:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, true, 0x000000FF);
fadeOutTarget.draw(imageContainer);
// Paint the BitmapData snapshot into a bitmap
var fadeOutBitmap:Bitmap = new Bitmap(fadeOutTarget);
addChild(fadeOutBitmap);
// Remove the sprite containing the vectors.
removeChild(imageContainer);
// Tween to fade out
var fadeOut:Tween = new
Tween(fadeOutBitmap, "alpha", Strong.easeOut, 1 , 0, 78);
This article demonstrates how easy it is to use ActionScript to create an animation. Now you are ready to add interesting effects to your rich media projects with a minimal amount of work. To learn more about working with ActionScript 3, visit the ActionScript Technology Center to find online tutorials, book excerpts, and sample files. To look up syntax and research usage information, see the detailed Flash Professional online documentation.
Experiment with creating different types of animations and explore how you can reuse the tweens in your projects. As you become more familiar with working with the transition and Tween classes, and using the Copy Motion as ActionScript 3 command, you'll be able to dive deeper into the possibilities of dynamically generating motion XML definitions and find new ways to apply these strategies when developing your own ActionScript 3 classes.
| 04/23/2012 | Auto-Save and Auto-Recovery |
|---|---|
| 04/23/2012 | Open hyperlinks in new window/tab/pop-up ? |
| 04/21/2012 | PNG transparencies glitched |
| 04/01/2010 | Workaround for JSFL shape selection bug? |
| 02/13/2012 | Randomize an array |
|---|---|
| 02/11/2012 | How to create a Facebook fan page with Flash |
| 02/08/2012 | Digital Clock |
| 01/18/2012 | Recording webcam video & audio in a flv file on local drive |