Archive for May, 2007

Copy Motion to AS3 (ActionScript 3)

One of the new features we have in Flash CS3 is the ability to copy an animation on the timeline to AS3 (ActionScript 3). I am a big fan of this new feature let me show you why.

For example:

the animation that is illustrated above is a typical timeline animation. If you then right click on the timeline you would see the option to copy motion to AS3.

It then asks you to specify and instance name of the symbol to which you would like to apply this code too. Flash CS3 then places code into the clipboard. If you were to paste this code in the actionscript panel you would see:

import fl.motion.Animator;
var box_xml:XML =
<Motion duration="1" xmlns="fl.motion.*" xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
<Source frameRate="30" x="52" y="111.5" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="box">
<geom:Rectangle left="0" top="0" width="92" height="77"/>
<geom:Point x="0.5" y="0.5"/>

<Keyframe index="0" tweenSnap="true" tweenSync="true">
<SimpleEase ease="0"/>

var box_animator:Animator = new Animator(box_xml, box);;

Notice that the code in red is the only part that truly is AS3. The blue part is XML describing the animation.

To get this to work, just create a new AS3 document and paste the code on frame 1 of the timeline and drop any symbol on stage and call it’s instance ‘box’. Run the movie and you will see the symbol move across the stage.

Ok,so what’s so cool about this? well, first. It allows me to re-use an animation as many times as I want. It also allows a normal designer/animator to work with a developer that prefers to see everything in code. However, one of best parts is that it allows me to store my animations as external XML files.

If instead of right-clicking on the timeline, I would have gone to the command menu and selected "Export Motion’. I would then be able to save just the XML description to an external file.

ok, so now what. Well, lets say I saved my animation as swirl.xml, if I change my AS3 code a little. Like so:


import fl.motion.Animator;

var green_can_xml:XML = new XML();
var green_can_animator:Animator;
var XML_URL:String = "swirl.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);

function xmlLoaded(event:Event):void {
green_can_xml = XML(;
green_can_animator = new Animator(green_can_xml, green_can);

I can now have my flash movie load the animation at runtime and play it. This will allow me to change the behavior of the animation just by replacing an XML file. Cool huh? I’ll let you figure out all the uses fot it.

Oh, and in case you are wondering the same animation can then be applied to a component in Flex. I’ll show how to do that next post.