By Dan Carr
 
Created
30 April 2010
 

Requirements

 
Prerequisite knowledge

This article is aimed at designers and developers currently working in Flash Professional with an interest in learning more about using well-structured ActionScript code with their SWF-based content. While this article will cover animation concepts to some degree, it's assumed that the reader has experience using the tools in Flash Professional.
 

 
User level

Intermediate
 

 
Required products

 
Sample files

  • animation_flash_fbuilder_as3.zip (2794 KB)
The introduction of Adobe Flash Builder 4, an Eclipse-based IDE for ActionScript 3 and Flex framework development, has given Flash developers the opportunity to take advantage of a highly productive code development environment while continuing to use Adobe Flash Professional for the creation of interactive content.
 
The use of class-based ActionScript code (as opposed to timeline-based ActionScript code) with Flash Professional content may be new for many designers, but the benefits of reusable code can be significant when working on anything other than trivial projects. This approach also opens up new workflows for developers and designers to work together, with clearer separation between the design and logic within a project.
 
This article provides an overview of the new Flash Builder 4 and Flash Professional CS5 integration features and demonstrates the enhanced workflows through the creation of a simple character animation controlled by an ActionScript class. (Click the buttons in Figure 1 to interact with the final animation.) In addition, you'll bring the completed work into a Flex project, and learn how to reuse content and visual components within rich Internet applications (RIAs).
 
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.
Figure 1. Simple project you build in this tutorial, showing buttons that trigger the MovieClip to play animations using ActionScript (click the buttons to interact with the sample)
 
Note: The tutorial steps in the sample project are purposefully simple because we assume you already know the basics of animation in Flash Professional. Therefore this article focuses on the technical aspects of combining ActionScript with MovieClip symbols.
 

 
Understanding the tools and workflow

This section provides an overview of the tools and the workflow you'll cover in the sample project. If you're comfortable with the tools in Flash Professional you might want to skim this section or skip directly to the tutorial. If you're new to Flash Professional and Flash Builder, read on.
 
 
Working with Flash Professional CS5
Flash Professional is primarily geared for developing animation and visual content with features supporting design-friendly production. In the beginning, the most exciting thing about using Adobe Flash Player was the ability to display lightweight vector content on the web; as Flash Player capabilities continued to expand, the range of animation features in Flash Professional also grew to support a wider range of creative tasks.
 
More recent versions of Flash Professional have included some great feature updates for visual designers. Flash Professional CS4 (and Flash Player 10) introduced 3D rotation and animation tools, the Bone tool for creating animated armatures, and an advanced type of motion tweening based on an XML definition of the motion in an animation (which allows for reusing and repurposing visually generated animations across timelines and projects). Flash Professional CS5 continues to build the visual developer's toolbox by introducing improved text support using the Text Layout Framework and a new type of font embedding using the Compact Font Format (CFF). Flash Professional CS5 also introduces improved workflows and integration with the Flex SDK and Flash Builder as a code development environment.
 
The first thing to understand is the file types you'll work with:
 
  • FLA: When you create a new file in Flash you're creating what's known as a FLA file. The FLA file is the editable master file that you'll use to build and publish content, similar in concept to a PSD file in Photoshop. You'll keep this file as part of the source files for your project and return to it for editing, but you will not publish it to your server for viewing. FLA files end in the .fla suffix.
  • SWF: When you want to distribute your work so other people can see it, you'll publish a SWF file from the FLA. The SWF is a compressed non-editable version of the FLA file, similar in concept to exporting a JPG or PNG file from a PSD file. SWF files end in the .swf suffix.
  • HTML: When you publish the SWF from Flash Professional you also have the option of publishing the HTML page that embeds the SWF on a web page for viewing. This file is optional and can be created in other tools, but it's handy to be able to generate everything you need from Flash Professional. In the end, you'll upload the SWF and the HTML page to a server for viewing in a web browser.
While working in the tutorial you'll dive into the following Flash Professional CS5 workspace features:
 
  • Stage: The Stage is the area on the main timeline where you see your graphics and where they are placed in relation to the file dimensions of the Flash movie (SWF file). This area is similar to the Canvas or Artboard in other design tools.
  • Timeline: Flash content is organized through a series of movie clip symbols each containing a timeline. Each timeline is composed of layers and frames. Layers create separation of content similar to other design tools, and frames create a way to represent changes in content over time (animation or graphics states). When you create a FLA file you are presented with the main timeline as the default view. The main timeline is the root container for the file.
  • Library: All movie clips other than the main timeline are stored in the FLA document's library. The Library panel holds a collection of reusable objects. There is one library per FLA file. It contains reusable content including symbols, fonts, images, and embedded sounds and videos.
  • Symbols and instances: Symbols are definitions of reusable Flash objects. For example, a symbol might contain a graphic, an entire animation, or any other collection of assets. Symbols only exist in the library. When you use a symbol somewhere on a timeline, you're creating an instance of the symbol. The key concept here is that you can use as many instances of a symbol as you like without significantly increasing the file size of your movie. Symbols can be edited at any time, which causes an update in all instances.
  • Properties: To edit the individual symbol instances in unique ways, you work with the properties of the instances. Properties are variables that describe something about the instance. While symbol instances will always be the same as their parent symbol at their core, you can change properties of the instances to create unique variations by changing properties such as size, location, color, or transparency. This is a key concept in creating tweened animations. To edit instance properties you can use the Properties panel or ActionScript code attached to a timeline.
You'll get to know plenty of other features in Flash Professional in the following sections, but the preceding list covers the main elements. To learn more about the basics of the Flash Professional CS5 user interface see Flash workflow and workspace in the Flash online documentation.
 
 
Using Flash Builder 4
Flash Builder, previously called Flex Builder, supports the development of cross-platform RIAs using the open source Flex framework. Flex is essentially a collection of visual components and ActionScript classes designed to make developing applications more productive. Flex includes a declarative XML-based markup language alongside ActionScript, which appeals to many programmers with experience in other languages.
 
While Flex has become widely adopted as the leading way to develop RIAs that run in Flash Player, some developers preferred to use Flex Builder (and now Flash Builder) for pure ActionScript development (that is, without using the Flex framework).
 
Flash Builder introduces integration features with Flash Professional CS5 that allow Flash developers to combine the strengths of Flash Builder with the strengths of Flash Professional. While it is possible to create and edit ActionScript files in Flash Professional, the Flash Builder workflow is a huge improvement. The change in the product name acknowledges that developing content for Flash Player has expanded beyond Flash and Flex and now encompasses combined workflows across several tools in what is now called the Flash Platform.
 
One strength of Flash Builder is its ability to create and manage code. It offers expanded support and shortcuts for generating ActionScript files, working with code hints to speed along the coding process, compile-time code checking, and debugging tools.
 
Here are some of the file types you'll encounter in the workflow:
 
  • AS: In the Flash Professional / Flash Builder workflow, you'll create ActionScript files in Flash Builder. ActionScript files in general are called classes. An ActionScript class defines a reusable object in code similar to the way a symbol defines a reusable visual object in Flash. ActionScript classes are stored in a folder structure called a package. You'll learn more about the concept of classes in the sections that follow (and don't worry if you're new to this, it's easier than it sounds). ActionScript files end in the .as suffix.
  • MXML: MXML is an XML-based markup language used by the Flex SDK to create Flex-based SWF files. MXML files are only used with Flex projects and are not used with Flash Professional projects, but they are worth mentioning as they are a cornerstone of working in Flex. MXML is a term that you'll see often when working with Flash Builder.
  • HTML, XML, CSS: Flash Builder also allows you to edit text files based on other standard web technologies.
While working in Flash Builder in the tutorial you'll use the following workspace features:
 
  • Code editor: The code editor is the central view in the workspace where you'll see the code you're writing in the ActionScript file.
  • Package Explorer: The Package Explorer usually appears on the top left of the user interface and gives you a clear view of the files in your Flash Builder project. You can use this view to launch files and visually manage the assets while working in the project.
  • Outline: The Outline view shows the various elements in your ActionScript file including variables and functions. You can use this panel to see an overview of the contents of a file and to jump to specific areas of the file without scrolling. This is particularly handy when you develop a large script (which is an easy thing to do once you get rolling).
  • Problems: The Problems view shows you identifiable coding errors in your ActionScript files. This feature evaluates the code in the project every time you save the file. This real-time error checking feature is a big time saver because it enables you to see your issues as you go. It also allows you to jump directly to the lines of code that are causing the errors.
To learn more about the basics of the Flash Builder user interface, see Flash Builder workbench basics in the Flash Builder online documentation (especially the section, "The Flash development perspective").
 
 
Combined workflow
The new workflow integration allows you to use Flash Professional as you normally would and use Flash Builder in two main ways: as a code editor for speeding along ActionScript development, and as a real-time debugging tool for your code. The beauty of the workflow from a Flash developer's perspective is that you'll be able to do most things the way you already do them with the added benefit of launching Flash Builder whenever you need to develop code. On the Flash Builder side of things the workflow also feels familiar even down to being able to press Control+Enter (Windows) or Command+Return (Mac) to launch the Test Movie mode in Flash Professional.
 
 
Understanding the sample project structure
If you're familiar with writing actions and ActionScript code in Flash Professional, you may be asking yourself why you would want to use a second tool for code development. (I recall asking myself that years ago when I started using a text editor along with Flash Professional.) The answer is that it will take you less time to create code that is better organized, easier to follow and understand, and ultimately reusable across projects. In addition, moving to Flash Builder provides more support for coding shortcuts and debugging along with creating a separation of your code from the FLA file.
 
In the next section, you'll save your FLA file and ActionScript files into the supplied project folder. The FLA file will include a library structure containing bitmap images and a symbol, which you'll control with ActionScript to create an animation.
 
In the Flex portion of the tutorial your work will be saved into the default workspace folder for Flash Builder 4 files: [user]/Flash Builder 4/FlexCharacterAnimation/src.
 

 
Tutorial: Combining animation and ActionScript

An application programming interface (API) is simply the names of the variables and functions assigned to an object that either describe the object or make it do something. For example, if you create an animation in a movie clip symbol, you can use the movie clip's ActionScript API to start and stop the timeline (play() and stop() are examples of functions in the MovieClip API). You could also determine which frame the animation is on by using the movie clip's currentFrame property (currentFrame is an example of a property in the MovieClip API). You probably have some experience using the play() and stop() actions in Flash Professional to control timelines. This tutorial will show you how to create a custom API for a simple character animation including controls that trigger specific graphic states. Along the way you'll learn how to use best practices for writing ActionScript code.
 
 
The big picture
The following series of steps will lead you through the process of setting up graphic assets in a symbol and then controlling them via ActionScript. If you're familiar with building animations in symbols already then you know many of the steps. The difference in this workflow is that you'll section off frames in the timeline with stop actions and frame labels. Instead of playing straight through the timeline as you would in a regular animation, you'll use ActionScript to control the timeline and jump to specific frames on command.
 
On the ActionScript side of the development tasks you'll expose the frame labels and sections of the animation to the code environment. You'll do this by writing a simple script format including properties matching the frame labels and shortcut functions that trigger the symbol to display the graphic states. To take it a step further, you'll create a second script that will trigger the animation to play based on a sequence of states defined in an animation queue. The result will be both the definition and implementation of code controls for your symbol.
 
The benefit of this approach is the ability to dynamically control the animation at runtime using ActionScript. That means that you can randomize movement, play data-driven sequences of animation states, and respond to user interaction in a visually interesting way, among many other possibilities.
 
 
Start by setting up the project
It's usually a good idea to start in an organized way and develop your projects in a folder dedicated to the project. I commonly create a client or organization folder and then create project folders inside of that.
 
Follow these steps to set up the project:
 
  1. Download the sample ZIP file for this article and unzip it on your desktop.
  2. Open the resulting folder and examine its contents.
The project folder will be the root folder for your work during the course of the tutorial. You'll save your FLA file and ActionScript files in this folder.
 
The project_completed folder contains the finished working sample for the tutorial. Included you'll find a flash folder containing the finished work from the first part of the tutorial and a flex folder containing the same files modified for the Flex project sample. You can reference these files and deconstruct them if you run into problems.
 
 
Build an animation in Flash Professional CS5
The next step is to build the graphic states used as a visual focal point for the project. The graphic states will represent the expressions of an avatar character that can be controlled by buttons or ActionScript. The tutorial will walk through the basic steps involved with creating the character including expression states, a logo or label, and an ActionScript API for controlling the animation at runtime. For the purposes of simplicity the symbol will be built as a frame-by-frame animation using supplied graphics.
 
The character animation will include graphics that appear to make the character's eyes track through the following states (see Figure 2): Default, Blink, Look Left, Look Right, and Look Up.
 
The five graphical states represented in the character animation
Figure 2. The five graphical states represented in the character animation
Follow these steps to set up your FLA file:
 
  1. Open Flash Professional CS5 and create a new ActionScript 3.0 FLA file by choosing File > New > ActionScript 3.0. Name the file CharacterAnimation.fla and save it into the project folder next to the assets folder.
  2. Create a new movie clip symbol in the library (Control+F8 / Command+F8). In the Symbol Properties dialog box, type Character for the Name and select Movie Clip as the type.
  3. Click OK to accept the settings for the new symbol.
    At this point you've left the main timeline and are now viewing the Character symbol's timeline.
     
    Since you know the states of the animation you want to create, this is a good time to set up the structure of the Character symbol timeline. To divide the states inside of a single movie clip timeline, you can use keyframes and frame labels to visually section off the timeline.
     
  4. Start by naming the existing layer assets.
  5. Click on Frame 50 of the timeline and press F5 to extend the timeline 50 frames.
    In this sample the timeline won't play straight through the frames as it would in a tweened animation. Instead you'll space out the graphic states and use ActionScript to jump to the appropriate frames.
     
  6. Add a layer above the assets layer and name it actions. When adding actions to a timeline it's considered a best practice to create an actions layer dedicated entirely to ActionScript. Grouping ActionScript "code" on this layer makes the file easier to manage.
  7. Click on Frame 1 of the actions layer and open the Actions panel by choosing Window > Actions.
  8. Type stop(); in the panel's text editor.
  9. Add a layer above the actions layer and name it labels.
  10. Select Frame 1 of the labels layer and type default as the Label Name in the Properties panel.
  11. Click on Frame 10 on the labels layer and press F6 to add a keyframe.
  12. Select the new keyframe and add the frame label blink to it.
  13. Repeat this process to add labels to the following frames:
    • Frame 20: look_left
    • Frame 30: look_right
    • Frame 40: look_up
Now you're ready to add artwork to your Character symbol. The workflow here assumes that you've already created your graphics in another graphic program and have images ready to assemble. Of course, you can create your artwork in Flash as well.
 
Follow these steps to import artwork and complete the symbol layout:
 
  1. Return to the timeline of your Character symbol.
  2. Click on Frame 1 of the assets layer and import the first image by choosing File > Import > Import to Stage.
  3. In the dialog box that appears, browse for the Charater_default.jpg file in the project/assets folder and click OK. Notice that the image appears on the keyframe at Frame 1.
  4. Add a new keyframe to the assets layer by selecting Frame 10, and pressing F6.
  5. Import the Character_blink.jpg file to the new keyframe.
  6. Repeat the process to import the remaining images and place them on the following frames:
    • Frame 20: Character_look_left.jpg
    • Frame 30: Character_look_right.jpg
    • Frame 40: Character_look_up.jpg
  7. It's a good idea to organize your library by adding a folder to hold the bitmaps you just imported. Click on the New Folder button (the folder icon) on the lower left of the Library panel and name the new folder bitmaps.
  8. Drag the bitmap images into the new folder.
  9. Save your file.
Follow these steps to import artwork for a logo or a label:
 
  1. Return to the timeline of your Character symbol.
  2. Click on Frame 1 of the assets layer and add a new layer above it named logo.
  3. Import the logo.jpg file from the assets folder in the supplied files and position it in the lower right of the character or wherever you prefer. You can import your own artwork or add a text label in this step as well. The concept here is that you can add graphics on frame 1 of the Character timeline, which you'll see across all of the expression states.
  4. Save your file.
At this point you've set up the basic elements of the character animation states (see Figure 3). Using ActionScript you can make these static frames appear as a frame-by-frame animation by showing them in sequence with timing determined in the code. Of course, you can also create nested animations including tweens and other frame-by-frame animations as desired (that is, when you jump to the blink state, the keyframe can hold a nested movie clip containing its own animation).
 
The Character symbol's timeline showing the structure of layers, frame labels, and keyframes
Figure 3. The Character symbol's timeline showing the structure of layers, frame labels, and keyframes
 
Create an ActionScript API for the animation
After completing the set up of the symbol's timeline, you can create an ActionScript API to gain programmatic control over the visual assets in the FLA file. The first step is to create an ActionScript class that declares the states of the symbol to any other ActionScript object that might want to know.
 
An ActionScript class is a text file containing ActionScript code written in an predefined format. The class keywords and syntax used in the format are always used in the same way. Once you've written an ActionScript class you can assign it to the main timeline or any symbol's timeline in the library.
 
Follow these steps to create an ActionScript class for the symbol:
 
  1. Right-click the Character symbol in the Library panel and select Properties.
  2. In the Symbol Properties dialog box, click the arrow next to Advanced if the advanced options are not already showing.
  3. Select Export For ActionScript to enable the symbol linkage. This makes the symbol accessible to instantiation via ActionScript and it forces the symbol to export with the SWF. Notice that the value in the Class text box is set to the symbol name by default. Now the new Flash/Flash Builder integration features come into play.
  4. Click the Edit Class button (pencil icon) next to the Class text box.
  5. When you are asked if you want to edit the class in Flash Professional or Flash Builder (see Figure 4), choose Flash Builder and click OK.
The Symbol properties and Edit ActionScript 3.0 Class dialog boxes
Figure 4. The Symbol properties and Edit ActionScript 3.0 Class dialog boxes
Flash Builder launches and displays the Create A New Flash Professional Project dialog box (see Figure 5). This step associates the Flash Builder project with your FLA file and project folder.
 
The Create a New Flash Professional Project dialog box
Figure 5. The Create a New Flash Professional Project dialog box
  1. Click Finish. Flash Builder continues the project set up by automatically defining an ActionScript class with the same name as the FLA file and then proceeds to open the New ActionScript Class dialog box (see Figure 6). You can see in the Superclass setting that Flash Builder is generating an ActionScript class that extends MovieClip. A superclass is a script that another script inherits functionality from. In this case since the Character class subclasses MovieClip, it's the same as saying that Character is a MovieClip and therefore contains all the functions and properties of a MovieClip.
The New ActionScript Class dialog box
Figure 6. The New ActionScript Class dialog box
  1. Click Finish to generate the class.
  2. In Flash Builder, take a look at the default code applied to the Character.as file. These are the basic skeleton elements of an ActionScript class. Here's a quick breakdown of what you're looking at:
01 package 02 { 03 import flash.display.MovieClip; 04 05 public class Character extends MovieClip 06 { 07 public function Character() 08 { 09 super(); 10 } 11 } 12 }
  • Line 1 defines the package (folder) where the file is located. In this case there is no subfolder to indicate here, because the ActionScript file is sitting directly next to the FLA file.
  • Line 3 imports the MovieClip class, so that it can be referenced locally in this ActionScript file.
  • Line 5 declares the class name and declares that the class extends the MovieClip object. That's the same as saying that this script is a movie clip object and therefore has access to all of MovieClip's properties and functions.
  • Line 7 declares the constructor function. The constructor function is the core of the ActionScript class and always shares the name of the class. The constructor is significant because it gets called immediately when the class initializes. Classes are initialized when you create a new instance of them similar to the way a symbol is initialized when it's instantiated. You can place code inside the constructor function so that it will execute immediately when each instance of the class instance is created. This is handy for initializing variables and data related to the class.
The next step is to add properties that define the frame labels. To do this you add what are called constant static properties. Constant means that the values never change and static means they are associated with the class definition and therefore can be referred to directly from the class name. The purpose of this step is to expose the frame labels in a programmatic way so that you can see them in code hints and allow the text editor to enforce the correct names while you're coding.
 
  1. Add the following code to line 7 of the Character.as file, immediately above the constructor function:
//******************* // Constants: static public const DEFAULT:String = "default"; static public const BLINK:String = "blink"; static public const LOOK_LEFT:String = "look_left"; static public const LOOK_RIGHT:String = "look_right"; static public const LOOK_UP:String = "look_up"; static public const PAUSE:String = "pause";
Now that the frame labels are exposed to the code environment, you can simply use the code hints to find the label names and use gotoAndStop to navigate to any of those frames. However, it can be advantageous to create a new function in your API to handle navigation.
 
  1. In this sample, add the following code on line 21, immediately after the constructor function:
//******************* // Methods: public function showState( label:String, play:Boolean=false ):void { // Pause the current state... if( label == Character.PAUSE ){ return; } if( play ){ gotoAndPlay(label); }else{ gotoAndStop(label); } }
The showState() function accepts two parameters when you call it. The first is the frame label to navigate to and the second defines whether you call gotoAndPlay() or gotoAndStop() on that frame. The conditional statement at the beginning checks to see if the label is "pause", in which case it pauses on the current state by returning out of the function. This feature is handy when working with more complex multiframe animation states.
 
  1. Finish off the script with a few shortcut functions for convenience. Add the following code on line 33 after the showState() function:
//--------------- // shortcuts public function blink():void { showState(Character.BLINK); } public function lookLeft():void { showState(Character.LOOK_LEFT); } public function lookRight():void { showState(Character.LOOK_RIGHT); } public function lookUp():void { showState(Character.LOOK_UP); }
Calling any of the shortcut functions in turn calls the showState() function passing it the correct constant static property as the label. The showState() function definition sets the play parameter to false by default. You can use the second parameter to go to the frame label and play instead if that suits your animation. That said, you don't want to do that in this sample as there are no stop actions separating the graphic states.
 
  1. Save your file.
Because you launched Flash Builder from the Symbol Properties dialog in Flash Professional, the ActionScript class you just wrote is already connected to the Character symbol back in the FLA file's library.
 
Before moving on, take a look at your project folder and notice that Flash Builder has saved the Character.as file and CharacterAnimation.as file next to the FLA. In the next section you'll use the CharacterAnimation.as file to create an animation with the Character symbol.
 
 
Use the document class to implement the animation
In the last section you assigned the Character.as class to the Character symbol using the Symbol Properties dialog box. The result is that the code behaves as if you had written it on Frame 1 of the symbol's timeline (without all the ActionScript class syntax). The benefit of using the external ActionScript class is that you can assign it to any number of animation symbols using the Base class setting in the Symbol Properties dialog box. This is really handy if you're creating a range of different characters that all have the same behavior but different graphics.
 
In a similar way you can assign an ActionScript class to the main timeline. You do so by typing the class name as the Document Class in the Document properties. In the steps that follow you'll create a document class that instantiates the Character symbol and creates a looping animation using ActionScript and the symbol's code API.
 
Follow these steps to create the document class:
 
  1. Return to the main timeline in Flash.
  2. Click on the Stage to show the Document properties in the Properties panel.
  3. Type CharacterAnimation for the Document Class (see Figure 7). What you're doing is specifying the class name (class path) of the CharacterAnimation.as file. Note that when you reference the file in ActionScript you do not include the filename extension.
The Document properties seen in the Flash Properties panel
Figure 7. The Document properties seen in the Flash Properties panel
  1. Click the Edit Class Definition button (pencil icon) next to the Class to launch Flash Builder and edit the script.
    In Flash Builder, you'll see that the CharacterAnimation class has the same skeleton structure described earlier. The only difference is that the class extends Sprite instead of MovieClip (a Sprite is a MovieClip with only one frame).
     
    In CharacterAnimation.as you'll use a Timer object to drive the animation.
     
  2. Start by importing the Timer and TimerEvent classes; add the following code to lines 4 and 5 of the file:
import flash.events.TimerEvent; import flash.utils.Timer;
You're going to use the timer to call an event handler function at an interval. You'll create an animation queue of Character symbol states and play through the queue in sequence every time the timer calls the function. So the next step is to add variables to the script to use while generating the animation sequence.
 
  1. Add the following code to line 9 of the file:
//******************* // Properties: public var target:Character; public var states:Array; public var state:uint = 0; public var timer:Timer; public var timerDelay:Number = 1000; // in milliseconds
The target property will hold an instance of the Character symbol. The states property will hold a list of frame states to play in sequence as an animation queue. The state property holds a reference to which state is being displayed. And the timer and timerDelay properties define the timer and delay between playing states in the queue.
 
Next you'll add code to the constructor function, which will execute as soon as the main timeline loads and start the animation.
 
  1. Create an instance of the Character symbol by adding the following code to line 20 of the file, inside the constructor:
// Create character instance target = new Character(); target.x = (stage.stageWidth - target.width) / 2; target.y = (stage.stageHeight - target.height) / 2; addChild(target);
When you activated the Character symbol's Export For ActionScript option, the symbol became available to ActionScript in the movie. The line target = new Character(); instantiates a symbol with ActionScript using the new keyword. This is the equivalent of dragging an instance to the Stage from the Library panel. Notice that since the Character symbol is a movie clip, you can use its x and y properties or any other movie clip property in addition to the custom API you added to it.
 
  1. Build the animation queue using an array by adding the following code to line 26, immediately below the code you just added:
// Create the animation queue states = new Array(); states = new Array(); states[0] = Character.BLINK; states[1] = Character.DEFAULT; states[2] = Character.LOOK_LEFT; states[3] = Character.LOOK_RIGHT; states[4] = Character.DEFAULT; states[5] = Character.BLINK; states[6] = Character.LOOK_UP; states[7] = Character.DEFAULT; states[8] = Character.BLINK; states[9] = Character.DEFAULT;
Notice the numbering pattern of the indexes in the array. You can add and remove states following the same pattern. In this simple example you're only visiting the frame labels once before looping, but you can create any combination of states in the sequence and any length of animation queue you like. Just make sure to set up the queued states in the order you want them with the array indexes starting at 0 and counting upward.
 
  1. Finish off the constructor function code by initializing the timer and starting the animation; add the following code to line 34, immediately after the code above:
// Create a timer to drive the animation timer = new Timer(timerDelay); timer.addEventListener(TimerEvent.TIMER, onTimerTick); timer.start();
Lastly you need to advance the character's state based on the animation queue. This is done in the event handler for the timer you set up in the constructor.
 
  1. Add the following code to line 43, after the closing bracket of the constructor function:
//******************* // Events: private function onTimerTick(event:TimerEvent):void { // Show state from queue target.showState(states[state]); // Show next state next time around state++; // Loop if we've reached the end of the queue if( state == states.length ){ state = 0; } }
  1. Save the file.
You've created a simple yet scalable animation structure using a Flash symbol and ActionScript classes.
 
 
Test your work
Now that you have something to look at, it's a good idea to test your work. One of the great things about the new Flash Builder integration is the ability launch Flash Professional from Flash Builder to run the Test Movie command, launch the debugger, or publish your Flash project for deployment.
 
When you're ready to preview your work, press Control+Enter (Windows) or Command+Return (Mac) in Flash Builder to switch back to Flash Professional and launch the Test Movie command.
 
You should see the Test Movie command work as usual in Flash, publishing the SWF preview. After you watch the simple looping animation you built, close the SWF and you'll return to the Flash Builder workspace.
 
If you run into problems you can launch the ActionScript 3 debugger from the Flash Builder workspace to try to figure out what's going on. Assuming that your file is working at this point, you'll need to inject a bug to experience going through the debugging process. You can do this by declaring an object without instantiating a value and then trying to call properties or methods from the object instance.
 
Follow these steps to run the debugging workflow from Flash Builder:
 
  1. In Flash Builder add the following two lines of code after the open bracket of the constructor function (line 20) in CharacterAnimation.as:
var nullObject:Array; var length:uint = nullObject.length;
These lines won't trigger any author-time error checking in Flash Builder, but they will cause a runtime error in Flash Player.
 
  1. Launch the Test Movie command in Flash; a runtime error will appear in the Flash Output panel:
TypeError: Error #1009: Cannot access a property or method of a null object reference. at CharacterAnimation()
  1. Return to Flash Builder and add a breakpoint at the suspected problem location by right-clicking just to the left of the line number on line 26 and selecting Toggle Breakpoint to turn on a breakpoint at that line.
    Breakpoints suspend execution of the SWF and allow you to inspect all the available variables in the debugger, which is particularly useful for null value errors and errors that can't be seen clearly otherwise.
     
  2. Click the Debug Movie In Flash Professional button (bug and Flash icon) on the Flash Builder toolbar at the top of the screen.
    Flash launches, the movie plays, and then it immediately stops on the breakpoint you set. The debugger opens the CharacterAnimation.as file and points you to the line where the breakpoint is and the location where the script is throwing an error (if any). With this information you can either edit the code in Flash Professional or in Flash Builder to fix the problem. The key concept here is that you were able to place a breakpoint at a line of code, which stops the SWF execution at that line when in debugging mode. Once the debugger pauses execution you can review the state of variables as the SWF is executing to expose null values and other issues.
     
  3. Return to Flash Builder and remove the two lines of code.
  4. Test the movie again to confirm that everything works as expected.
  5. Save the file.
    If all is well and you're ready to post your file to the web, you can publish the SWF and HTML page from either Flash Builder or Flash Professional.
     
  6. To publish the project from Flash Builder, click the Publish In Flash Professional button on the toolbar at the top of the screen.
The view switches back to Flash Professional, which publishes the HTML file and SWF to the project folder. Examine the project folder to see the files produced by the project.
 
Note: If nothing happens when you click the Publish In Flash Professional button in Flash Builder, make sure there are no errors in the file and that you have the correct project selected in Flash Builder.
 
That's it. You've completed the first part of the Flash Builder integration workflow tutorial.
 

 
Going further: Using your Flash project in Flex

With the growing popularity of the Flex framework for RIA development, it's not uncommon to be tasked with preparing your Flash Professional work for use in a Flash Builder project. This is particularly common for animations and content that can be built more easily in Flash Professional than in Flex.
 
This section shows you how to convert your animation into a Flex-friendly component and the first steps of implementing the component in Flex.
 
 
Prepare your work in Flash Professional
The first thing to do is to prepare your Flash content for use in the Flex framework. This is easy to do in Flash Professional CS5 by running the Convert Symbol To Flex Component command.
 
In the following steps you'll convert the Character symbol into a component for use in the Flex framework.
 
Follow these steps to prepare your content:
 
  1. In Flash Professional, remove the document class definition by deleting the class name from the Document properties in the Properties panel (click on a blank area of the Stage if you don't already see the Document properties).
    Now you're ready to convert the Character symbol into a Flex components. To do this you need to add the FlexComponentBase SWC to the FLA file and turn on the Export SWC option under the Publish Settings Flash tab. The FlexComponentBase SWC adds Flex framework-specific ActionScript to your file that makes your movie clips compatible with Flex.
     
  2. Select the Character symbol in the Library and choose Commands > Convert Symbol To Flex Component and the FlexComponentBase SWC will be added to the library.
    Note: If your symbol didn't have a custom class assigned to it, you would be done at this step. Because it does, however, you need to update the component class in Flash Builder to extend mx.flash.UIMovieClip instead of the standard flash.display.MovieClip. This is what the command tried to do, but it can't assign the base class when you've already defined it in Flash Builder. The workaround can be applied with a simple update to your scripts.
     
  3. Return to Flash Builder and change the import statement on the Character class to the following:
import mx.flash.UIMovieClip;
  1. Change the class name after the extends keyword from MovieClip to UIMovieClip:
public class Character extends UIMovieClip { ...
This change to the class along with the addition of the Flex SWC in the FLA file's library is all that is needed to prepare the file for the Flex framework. Return to Flash to complete the setup process.
 
  1. Right-click the Character symbol and select Properties. Confirm that the Base class setting is empty and click OK.
    The symbol's icon changes to a Flex icon (see Figure 8).
     
The FLA file's library after updating the Character symbol to a Flex-ready component
Figure 8. The FLA file's library after updating the Character symbol to a Flex-ready component
The final thing you need to do is export a SWC file for consumption in Flex. SWC files are basically ZIP files with a .swc extension. They contain a SWF file and metadata describing the SWF's content. SWCs are a standard file format for distributing SWF content in component form. Your FLA file was already configured for this when you ran the Convert Symbol To Flex component command.
 
  1. Choose File > Publish to export the SWC.
Notice that a file named CharacterAnimation.swc now appears in the project folder. (You will also find this SWC file in the sample project_completed/flex/libs folder.)
 
Note: It's important to align your Flash symbols' graphics to a 0, 0 coordinate in the top left of their timeline. If you don't, you will not have reliable positioning control over them in the Flex framework.
 
 
Create a Flex project in Flash Builder
Flex projects are defined and built entirely in Flash Builder. To incorporate your Flash Professional authored content, you add the SWC created in the last step to the Flex project's library folder.
 
Follow these steps to create a Flex project and add your SWC file:
 
  1. Return to Flash Builder and choose File > New > Flex Project.
  2. For the project name type FlexCharacterAnimation and click Finish to create the project.
    The project appears in the Package Explorer and a file named FlexCharacterAnimation.mxml is automatically generated and opened in the editor. The MXML file is an XML file that can contain both MXML markup and ActionScript enclosed in a <fx:Script> tag. You'll use this file to set up a simple user interface for testing your Flash components in Flex. Leave the file open for editing.
     
    Note: Flex stores the MXML files and other source files in the src folder in the Flex project folder.
     
  3. Add your Flash Professional authored content to the project by dragging the CharacterAnimation.swc file into the libs folder in the Flex project. You can move the SWC file in the Flash Builder Package Explorer or manually in the folder system on your computer. The file will appear in Package Explorer (see Figure 9).
The Package Explorer showing the FlexCharacterAnimation project
Figure 9. The Package Explorer showing the FlexCharacterAnimation project
 
Build a simple user interface to manipulate your Flash animation
To see your Flash Professional authored components in the Flex framework, you'll work with MXML to declare the components and add a couple of buttons to trigger the animation states. The end result will show two versions of the character on the screen where the CharacterAnimation instance is animating on its own and the Character instance states are triggered by the Flex buttons.
 
In these next steps you'll build a simple user interface. If you haven't worked in MXML before, this is a great way to get started and understand how to incorporate your Flash Professional project work in the Flex environment.
 
Follow these steps to build the sample user interface in Flex:
 
  1. Return to the FlexCharacterAnimation.mxml file in Flash Builder.
    Notice the <s:Application> tag, which is the wrapper for the application. The Application tag contains a number of xmlns attributes, which define namespaces (class paths) for content referenced in the file. Start by adding a new namespace identifying the local content in the libs folder.
     
  2. Update the Application tag with the xmlns:local="*" attribute as follows:
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:local="*" minWidth="955" minHeight="600">
This enables you to reference symbols in SWC files in the libs folder using MXML.
 
  1. Add the following code between the open and close Application tags:
<mx:VBox paddingLeft="50"> <mx:HBox paddingTop="50"> <local:Character id="character" x="100" y="100"/> </mx:HBox> <mx:HBox paddingTop="50"> <mx:Button label="Blink" id="btn1" click="{character.blink()}"/> <mx:Button label="Look Left" id="btn2" x="100" click="{character.lookLeft()}"/> <mx:Button label="Look Right" id="btn3" click="{character.lookRight()}"/> <mx:Button label="Blink" id="btn4" click="{character.lookUp()}"/> </mx:HBox> </mx:VBox>
Notice in the code above that you can reference your Character symbol using <local:Character. Also notice that the four buttons can trigger the Character symbol API through the MXML markup. The XML syntax seen here is common in Flex framework development and can be combined with ActionScript code.
 
For more information on writing MXML and ActionScript in Flex 4, see About MXML in the online Flex documentation.
 
 
Test your work
In Flex you don't have access to the Test Movie command as you do in Flash. To test your project you'll launch the SWF in a browser.
 
Follow these steps to compile and preview the Flex project:
 
  1. Click the Run Project (Run FlexCharacterAnimation) button on the toolbar at the top of the Flash Builder workspace to launch your project in a browser window. (Alternatively, you can choose Run > Run FlexCharacterAnimation.) You should see the character appear with a series of buttons below the artwork (see Figure 10). Click on the buttons to trigger the expression states.
The Character symbol as seen in the Flex application
Figure. 10 The Character symbol as seen in the Flex application
Note: If there are any errors that will keep you from running the project, they will appear in the Problems view.
 
After the project is built, the published files appear in the bin-debug folder.
 
  1. If the application is not working as expected, you can click on the Debug Project button (bug icon) next to the Run Project button to launch the Flash Builder debugging workspace.
    Note: You need to have the debug version of the Flash Player installed to be able to use the Flash Builder debugging workspace. Check out my article, Understanding ActionScript 3 debugging in Flash, for more information on working with the debugger in Flash Professional and Flash Builder.
     
  2. When you're ready to complete the project and post to your server, click the Export Release Build button (or choose Project > Export Release Build). In this case the published files will appear in the bin-release folder.
For more information on debugging and profiling your Flex applications in Flash Builder, see Debugging your applications in the Flash Builder online documentation.
 

 
Where to go from here

While the tutorial provided an introduction to the Flash Builder / Flash Professional / Flex framework workflows, the animated content was purposefully simple. For further exercises, you may want to expand the animation symbols with more frame-by-frame animations, tweened animations, and more realistic animation queue sequences. Given the code structure provided here your best bet would be to select each bitmap graphic in the Character symbol and convert the bitmaps into their own nested symbols. From there you can experiment with creating nested animations that better define the animation state concept presented in the article.
 
Check out the samples in the project_extras folder (in the supplied files) to see the tutorial taken to the next level using frame-by-frame animations for each character expression. The extra samples show the use of nested animations, return animations, and ActionScript code variations.
 
I encourage you to explore working with the Flex framework and combining workflows from Flash Professional and Flash Builder to expand your knowledge of Flash Platform integration. Good luck!
 

 
Acknowledgements

Thanks to Sam Hood for providing the cool artwork and animation frames for the sample files. You can check out more samples of Sam's Flash character animations at hoodness.com.