Beginners Guide to Getting Started with AS3 (Without Learning Flex)

If you're anxious to get started with ActionScript 3 but don't want to have to learn Flex or MXML, the form of XML Flex uses to design applications, this tutorial is for you. Here you will learn how to use the command line compiler (mxmlc.exe for the Windows platform) to compile and create SWF files that use ActionScript 3.

Using or own Flash CS3? If so this tutorial might not be for you. Instead check out Getting Started with ActionScript 3.0 in Adobe Flash CS3.

Obtaining the Compiler

To create SWF files from ActionScript, you will need a compiler, the program that interprets ActionScript code and translates it into the machine code used in SWF files. If you have Flex Builder 2 installed, you already have mxmlc.exe, the compiler that does this for MXML and ActionScript 3 files. If not, you can get a copy of mxmlc.exe by installing Flex Builder or downloading the Flex SDK, both of which are available from http://www.adobe.com/go/flex_trial/.

Flex Builder: If you've installed Flex Builder, you can find mxmlc.exe in the following directory (this may vary for custom installations):

C:\Program Files\Adobe\Flex Builder 2\Flex SDK 2\bin\mxmlc.exe

Flex SDK: If you've downloaded the SDK, save it to any location on your hard drive. Then, from that location, you can find mxmlc.exe in

[save location of SDK]\bin\mxmlc.exe

mxmlc.exe in the bin directory

Note: Bear in mind that to view ActionScript 3-published SWFs, you will need the Flash 9 player. Players are included with the downloads above or can be found on http://www.adobe.com/go/getflashplayer. You may also need to make sure that your swf file are associated with the version 9 Player so that when you open them, they will play correctly in the correct (v9) player.

Note: Some screen shots may be from older versions of the SDK and/or source files.

About mxmlc.exe

mxmlc.exe is a launcher that runs the MXML and ActionScript 3 compiler that converts MXML files (.mxml) and ActionScript 3 files (.as) into published SWF files (for the purposes of this tutorial, we will be primarily concerned with ActionScript 3 files though the compiler handles both as well as some other file types used in the ultimate generation of the SWF). The real compiler is a Java jar file located in the lib directory of your Flex Builder/SDK install and not mxmlc.exe itself. Because of this, to work with the compiler you'll A) need to make sure you keep all of those files of which the compiler is dependant (i.e. dont go moving around just mxmlc.exe and expect it to work), and B) need to have the Java runtime environment installed on your system. If you've installed Flex Builder you won't have to worry about this since it will take care of this for you. If you just got the SDK, however, and haven't had Java installed on your computer, you can download and install the Java runtime environment from http://java.sun.com.

In the directory containing mxmlc.exe you may notice some other executables. compc.exe is for creating SWC files (pre-compiled component file), and fdb.exe is the command line debugger. Here we are sticking to just using mxmlc.exe which is all you need to get started using ActionScript 3.

Using mxmlc.exe

When running mxmlc.exe, you'll need to supply it with at least (and usually) one ActionScript 3 file to compile. This file serves as the primary application file for the published SWF. Any other external ActionScript 3 files this application file imports or references will automatically be compiled into the resulting SWF. Unlike the Flash authoring environment or Flex Builder, though, mxmlc.exe has no GUI (graphical user interface); it is a command line tool. Trying to run it by double clicking and opening the EXE will cause a command prompt to pop up which will do some quick evalutation and immediately close. For it to work, it needs an ActionScript (or MXML) file to compile. To do this you have a couple of options.

Drag and Drop: The easiest way to supply an ActionScript 3 file to mxmlc.exe is to just use explorer to drag an AS file onto the EXE (or a shortcut to it). mxmlc.exe will be called targeting that ActionScript 3 file and will use the default options to compile and save the SWF in the directory in which the AS file was located.

Compile with mxmlc.exe using drag and drop

If there are any problems with the compilation, such as a syntax error in the ActionScript, a SWF will not be created and the command prompt will display the errors briefly, but immediately close once its finished not giving you enough time to read them.

Command Line: Using the command line, you can run mxmlc.exe for any file(s) with any configuration variables or options you need and be able to keep the prompt open for errors and other messages. You can open a command line prompt by typing cmd into the Windows Run dialog (Windows Key+R) and hitting enter or running Start > Programs > Accessories > Command Prompt . In the command line, you'll need to be able to reference both mxmlc.exe and your target AS file either absolutely or relatively from the current directory displayed by the command prompt. An easy way to do this, no matter what directory your command line is in is, again, using drag and drop. First drag mxmlc.exe into the command line, hit the space bar, and drag your AS file into the command line.

Command line calling mxmlc.exe

Note: Paths with spaces in them will need to be encased in quotes.

Hit enter and mxmlc.exe will compile the provided AS file in the same manner it would if you dragged the AS file onto the EXE only in the case of errors or other messages the command prompt window will remain open so that you can read them.

With just the ActionScript file, mxmlc.exe is called with one argument assigned to its default option (-file-specs). The command line also allows you to specify other options that can help you modify the behavior of the mxmlc.exe call. A list of these options are as follows:

-benchmark output performance benchmark -compiler.accessible alias -accessible

generate an accessible SWF -compiler.actionscript-file-encoding <string> alias -actionscript-file-encoding

specifies actionscript file encoding. If there is no BOM in the AS3

source files, the compiler will use this file encoding. -compiler.allow-source-path-overlap alias -allow-source-path-overlap

(advanced) -compiler.as3 alias -as3

uses the AS3 compatibility mode. default is true. Either -as3 or -es3

must be 'true'. -compiler.context-root <context-path> alias -context-root

path to replace {context.root} tokens for service channel endpoints -compiler.debug alias -debug -compiler.defaults-css-url <string> alias -defaults-css-url

(advanced) -compiler.doc alias -doc

(advanced) -compiler.es3 alias -es3

uses the ES3 compatibility mode. default is false. -compiler.external-library-path [path-element] [...] alias -el

list of SWC files or directories to compile against but to omit from

linking (repeatable) -compiler.fonts.languages.language-range <lang> <range> alias -language-range

a range to restrict the number of font glyphs embedded into the SWF

(advanced, repeatable) -compiler.fonts.managers [manager-class] [...] alias -managers

Compiler font manager classes, in policy resolution order (advanced) -compiler.fonts.max-cached-fonts <string> alias -max-cached-fonts

(advanced) -compiler.fonts.max-glyphs-per-face <string> alias -max-glyphs-per-face

(advanced) -compiler.fonts.system-search-path [path-element] [...] alias -system-search-path

(advanced, repeatable) -compiler.headless-server alias -headless-server

a flag to set when Flex is running on a server without a display

(advanced) -compiler.include-libraries [library] [...] alias -include-libraries

a list of libraries (SWCs) to completely include in the SWF

(repeatable) -compiler.incremental alias -incremental

enables incremental compilation -compiler.keep-all-type-selectors alias -keep-all-type-selectors

disables the pruning of unused type selectors (advanced) -compiler.keep-generated-actionscript alias -keep

save temporary source files generated during MXML compilation

(advanced) -compiler.library-path [path-element] [...] alias -l

list of SWC files or directories that contain SWC files (repeatable) -compiler.locale <string> alias -locale

specifies the locale for internationalization -compiler.namespaces.namespace <uri> <manifest> alias -namespace

Specify a URI to associate with a manifest of components for use as

MXML elements (repeatable) -compiler.optimize alias -optimize

Enable post-link SWF optimization -compiler.profile alias -profile

generate a movie that is suitable for performance profiling -compiler.services <filename> alias -services

path to Flex Data Services configuration file -compiler.show-binding-warnings alias -show-binding-warnings

toggle whether warnings generated from data binding code are

displayed -compiler.show-coach-warnings alias -show-coach-warnings

runs the AS3 compiler in a mode that detects legal but potentially

incorrect code -compiler.show-dependency-warnings alias -show-dependency-warnings

show warnings when dependencies cannot be determined at compile time

(advanced) -compiler.show-deprecation-warnings alias -show-deprecation-warnings

toggle whether the use of deprecated APIs generates a warning -compiler.source-path [path-element] [...] alias -sp

list of path elements that form the roots of ActionScript class

hierarchies (repeatable) -compiler.strict alias -strict

runs the AS3 compiler in strict error checking mode. strict must be

'false' when es3 is 'true'. -compiler.theme [filename] [...] alias -theme

list of CSS or SWC files to apply as a theme (repeatable) -compiler.use-resource-bundle-metadata alias -use-resource-bundle-metadata -compiler.verbose-stacktraces alias -verbose-stacktraces

save callstack information to the SWF for debugging (advanced) -compiler.warn-array-tostring-changes alias -warn-array-tostring-changes

(advanced) -compiler.warn-assigning-undefined-to-non-object-type alias -warn-assigning-undefined-to-non-object-type

(advanced) -compiler.warn-bad-type-cast alias -warn-bad-type-cast

(advanced) -compiler.warn-bad-undefined-comparision alias -warn-bad-undefined-comparision

(advanced) -compiler.warn-boolean-constructor-with-no-args alias -warn-boolean-constructor-with-no-args

(advanced) -compiler.warn-class-is-sealed alias -warn-class-is-sealed

(advanced) -compiler.warn-constructor-returns-value alias -warn-constructor-returns-value

(advanced) -compiler.warn-deprecated-event-handler-error alias -warn-deprecated-event-handler-error

(advanced) -compiler.warn-deprecated-function-error alias -warn-deprecated-function-error

(advanced) -compiler.warn-deprecated-property-error alias -warn-deprecated-property-error

(advanced) -compiler.warn-duplicate-func-def alias -warn-duplicate-func-def

(advanced) -compiler.warn-for-var-in-changes alias -warn-for-var-in-changes

(advanced) -compiler.warn-function-parameter-declared-as-void alias -warn-function-parameter-declared-as-void

(advanced) -compiler.warn-math-expressions-treat-null-like-zero alias -warn-math-expressions-treat-null-like-zero

(advanced) -compiler.warn-missing-namespace-decl alias -warn-missing-namespace-decl

(advanced) -compiler.warn-no-constructor alias -warn-no-constructor

(advanced) -compiler.warn-no-explicit-super-call-in-constructor alias -warn-no-explicit-super-call-in-constructor

(advanced) -compiler.warn-no-type-decl alias -warn-no-type-decl

(advanced) -compiler.warn-scoping-change-in-this alias -warn-scoping-change-in-this

(advanced) -compiler.warn-super-only-works-for-class-objects alias -warn-super-only-works-for-class-objects

(advanced) -compiler.warn-undefined-function alias -warn-undefined-function

(advanced) -compiler.warn-undefined-reference alias -warn-undefined-reference

(advanced) -compiler.warn-var-hidden-by-function alias -warn-var-hidden-by-function

(advanced) -compiler.warn-wrong-arg-type alias -warn-wrong-arg-type

(advanced) -compiler.warn-wrong-number-of-args alias -warn-wrong-number-of-args

(advanced) -compiler.warn-xml-class-has-changed alias -warn-xml-class-has-changed

(advanced) -debug-password <string> the password to include in debuggable SWFs (advanced) -default-background-color <int> default background color (may be overridden by the application code)

(advanced) -default-frame-rate <int> default frame rate to be used in the SWF. (advanced) -default-script-limits <max-recursion-depth> <max-execution-time> default script execution limits (may be overridden by root

attributes) (advanced) -default-size <width> <height> default application size (may be overridden by root attributes in the

application) (advanced) -dump-config <filename> write a file containing all currently set configuration values in a

format suitable for use as a flex config file (advanced) -externs [symbol] [...] a list of symbols to omit from linking when building a SWF (advanced,

repeatable) -file-specs [path-element] [...] a list of source files to compile, the last file specified will be

used as the target application (repeatable, default variable) -frames.frame [label] [classname] [...] alias -frame

A SWF frame label with a sequence of classnames that will be linked

onto the frame. (advanced, repeatable) -help [keyword] [...] keywords are 'syntax', 'list', 'advanced', 'aliases', 'details', or a

search term -includes [symbol] [...] a list of symbols to always link in when building a SWF (advanced,

repeatable) -lazy-init Enable/Disable ABC bytecode lazy initialization (advanced) -licenses.license <product> <serial-number> alias -license

(repeatable) -link-report <filename> Output a XML-formatted report of all definitions linked into the

application. (advanced) -load-config <filename> load a file containing configuration options (repeatable) -load-externs <filename> an XML file containing <def>, <pre>, and <ext> symbols to omit from

linking when building a SWF (advanced, repeatable) -metadata.contributor <name> alias -contributor

A contributor's name to store in the SWF metadata (repeatable) -metadata.creator <name> alias -creator

A creator's name to store in the SWF metadata (repeatable) -metadata.date <text> alias -date

The creation date to store in the SWF metadata -metadata.description <text> alias -description

The default description to store in the SWF metadata -metadata.language <code> alias -language

The language to store in the SWF metadata (i.e. EN, FR) (repeatable) -metadata.localized-description <text> <lang> alias -localized-description

A localized RDF/XMP description to store in the SWF metadata

(repeatable) -metadata.localized-title <title> <lang> alias -localized-title

A localized RDF/XMP title to store in the SWF metadata (repeatable) -metadata.publisher <name> alias -publisher

A publisher's name to store in the SWF metadata (repeatable) -metadata.title <text> alias -title

The default title to store in the SWF metadata -output <filename> alias -o

the filename of the SWF movie to create -raw-metadata <text> XML text to store in the SWF metadata (overrides metadata.*

configuration) (advanced) -resource-bundle-list <filename> (advanced) -runtime-shared-libraries [url] [...] alias -rsl

a list of runtime shared library URLs to be loaded before the

application starts (repeatable) -use-network toggle whether the SWF is flagged for access to network resources -version display the build version of the program -warnings toggle the display of warnings

These options follow the path to the application in the command prompt. They are preceded by hyphens and are usually followed by one or more space separated values. Note: you can obtain these options in the command list by running: mxmlc.exe -help list advanced details

Command to mxmlc.exe with additional options.

Batch (.bat) Files (preferred): Batch files are another alternative. They allow you to save command line commands to a text file that runs like an application. Using a batch file you can save your call to mxmlc.exe with any number of options and run those commands just by double clicking and launching a BAT. This tends to be the most useful approach to using mxmlc.exe. In fact, you may notice in the samples provided with both the Flex Builder and the SDK that there are build.bat files which are used to compile the project with mxmlc.exe.

Batch file launching mxmlc.exe

Using make.bat

In the source files provided with this tutorial you'll find a make.bat file. This batch file doesn't run mxmlc.exe to compile your ActionScript 3 files. Instead it was created to help you easily create the batch files that do. To use make.bat, just drag an AS file onto it. Then, a new batch file will be created with the name of your AS file that, when launched, will run mxmlc.exe and compile your AS file into a SWF. Additionally, the first time you run make.bat, it will automatically launch the BAT it creates for you. Before using make.bat, be sure to open it up in a text editor so you can set some variables letting you specify where your mxmlc.exe is located and set command line options. Otherwise the BAT files it creates will not function properly.

Editing make.bat Options

Create BAT with make.bat using drag and drop

When running a BAT created with make.bat, your AS file will be compiled using mxmlc.exe using the path you specified inside make.bat. If there are errors, the command line running mxmlc.exe will remain open showing those errors until you hit a key to continue, closing the prompt. In this case, no SWF is created and any pre-existing SWF will be deleted (the BAT does this, not mxmlc.exe). If the compile was successful, a new SWF will be created, overwriting any pre-existing SWF with the same name and it will automatically open for you to view. A command prompt will remain open in the background but will close when the SWF is closed.

Note: Using the -output (-o) option for mxmlc.exe to change the name of the published SWF, may cause make.bat-generated BAT files to function improperly

Working With ActionScript 3

Using mxmlc.exe doesn't help if you don't know ActionScript 3. Adobe labs (http://labs.adobe.com) has many resources to get you started with AS3. Some of the more important are the migration guide (http://www.adobe.com/go/AS2toAS3) and the language reference (http://www.adobe.com/go/AS3LR). These are good references but may not be the best for when you're just starting off.

I think its often helpful to start with the lowest common denominator–something that is very basic and gets you familiar with the minimum requirements for any kind of functionality. For that, we can create a simple class that has only what is necessary to get compiled by mxmlc.exe. Such a file has already been created for you and can found in the source files with the name BareBones.as. It consists of the following:

package {

import flash.display.Sprite;

public class BareBones extends Sprite {}

}

To quickly publish it using mxmlc.exe, just drag BareBones.as onto the mxmlc.exe file. The BareBones.swf will be automatically created for you with BareBones.as (there should be no errors so the messages in the command prompt are not important). To publish it with the help of make.bat, drag BareBones.as onto make.bat to create BareBones.bat (be sure that you changed the path in make.bat to point to your the location of mxmlc.exe on your system). The new BAT will automatically run compiling BareBones.as and running the resulting SWF. When you want to compile BareBones.as again, just double-click and open BareBones.bat (there will be no need to run make again).

Published BareBones.swf

The SWF, as you might have expected, is empty.

Taking a closer look at BareBones.as you'll notice that it consists of a single empty class file. This class, BareBones, extends the internal Sprite class which is imported from the flash.display package. To make use of the Sprite class at all in ActionScript 3, the import statement is required unlike in ActionScript 2 where it served only as a path shortener. Both the import statement and the class are contained within another block of code identified with the keyword package.

The package block is new to ActionScript 3. It lets you identify members of a package or groups of public code that can be imported into and used by other classes. If BareBones were in the com.senocular package, it would be saved as com/senocular/BareBones.as and be written as:

package com.senocular { import flash.display.Sprite; public class BareBones extends Sprite {} }

Unlike ActionScript 2, the package is no longer part of the class definition. Instead it is part of this new package block definition. Public classes not technically within a package still need to exist within a package code block as seen with the original BareBones class.

Was:

class path.path.ClassName { }

Now:

package path.path { class ClassName { } }

When published as a SWF, the BareBones class is associated with what in earlier versions of ActionScript was known as _root, or essentially the main timeline. This applies to all classes being published as the application class in mxmlc.exe. In order for that class to successfully have that association, it needs to be of the correct type and that means that it needs to be a subclass of Sprite or any other class derived from the Sprite class such as MovieClip (in case you were wondering, a Sprite is basically a movie clip without a timeline and frames). If you have a application class compiled by mxmlc.exe that is not derived from Sprite, you will get a runtime error when the SWF is played.

SWF root runtime error

As the root object, your class is immediately instantiated and that instance is added to the stage object in Flash. With that instantiation, the application class constructor is called and you have a starting place for your ActionScript 3 program to begin. Example:

package { import flash.display.Sprite; public class BareBones extends Sprite { public function BareBones(){ // begin coding here } } }

More will be covered about the structure of ActionScript 3 classes a little later on. First, lets look into making a viable example that will be capable of making something appear on the screen.

Display Objects in ActionScript 3

Objects you can see in the Flash player are known as display objects and are derived from the DisplayObject class. Such classes include, but are not limited to: Sprite, MovieClip (which is a subclass of Sprite), TextField, Bitmap, and Shape. All DisplayObject classes inherit from EventDispatcher so are inherently event-capable. In addition, the Sprite, MovieClip, and TextField classes (along with some others) inherit from the InteractiveObject class meaning they can recieve events from the mouse and keyboard such as mouseOver, click, and keyUp. Sprite and MovieClip also inherit from a class called DisplayObjectContainer meaning that they can contain other display objects within them. The application class of a SWF is derived from the Sprite class so it too is a DisplayObjectContainer. As such, it can add other classes to it as children.

The management of display objects in ActionScript 3 has completely changed. No longer do you use attachMovie, createEmptyMovieClip, or createTextField etc to create new MovieClip or TextField instances. Instead, you use the new keyword to create new instances of these objects and then add them to a DisplayObjectContainer using the addChild (or similar) method. If not added to a DisplayObjectContainer, the objects will exist and can be manipulated but are never seen as they will exist only in code. Once they are added to a DisplayObjectContainer, they can be easily removed or even added to some other DisplayObjectContainer at your leisure. The methods responsible for adding or removing instances from a DisplayObjectContainer include:

addChild

addChildAt

removeChild

removeChildAt

For more information on these and other related methods see the DisplayObjectContainer class documentation.

HelloWorld.as

The infamous "Hello World" example in ActionScript 3; creating and displaying the text "Hello World!":

package {

import flash.display.Sprite;

import flash.text.TextField;



public class HelloWorld extends Sprite {



public function HelloWorld() {

var display_txt:TextField = new TextField();

display_txt.text = "Hello World!";

addChild(display_txt);

}

}

}

Notice that the textfield used to display the text was created with new TextField and not createTextField as it would in previous versions of ActionScript. This textfield remained solely in code until addChild was used to attach it to the root HelloWorld class instance. Publish this as a SWF and you get the following:

HelloWorld.swf

Was:

MovieClip.createTextField();

Now:

DisplayObjectContainer.addChild(new TextField());

Graphics and the Drawing API

With ActionScript 3 also came some changes to the vector drawing API. Not only are there a couple of new methods such as drawCircle and drawRect, but the API is also no longer associated directly with MovieClip instances. Instead, the drawing API is now used on Graphics class instances. Those display objects which support dynamic drawings such as MovieClip, Sprite, and Shape now have graphics properties which are Graphics instances the drawing API is to be used with. When drawings are made within the graphics objects, they appear in the display object below any children that may have been added to them (assuming they are also DisplayObjectContainers, of which the Shape class is not).

As a Sprite, an application class will have a graphics property which can be used with the drawing API for the inclusion of dynamic drawings. As an example, see the Rectangles class:

package {

import flash.display.Sprite;

import flash.display.Shape;

import flash.display.Graphics;



public class Rectangles extends Sprite {



public function Rectangles() {



drawColoredRectIn(graphics, 0xFF0000);



var rect:Shape = new Shape();

drawColoredRectIn(rect.graphics, 0xFFFF00);

rect.x = 50;

rect.y = 50;

addChild(rect);

}



private function drawColoredRectIn(target:Graphics, color:int):void {

target.lineStyle(1, 0x000000);

target.beginFill(color);

target.drawRect(0, 0, 100, 100);

}

}

}

Results:

Rectangles.swf

Note that drawings within the graphics object of a DisplayObject instance appear below children of that instance.

Was:

MovieClip.lineStyle();

Now:

DisplayObject.graphics.lineStyle();

Embedding Assets Within a SWF

Without the Flash IDE, there is no way to import assets into your source files. Your source files are, afterall, just ActionScript text at this point. However, mxmlc.exe will recognize meta tags within the ActionScript that allow you to embed assets into the published swf and have those assets accessible as a custom class. The meta tag allowing you to do this is Embed meta tag.

The Embed meta tag is used to grab assets from an external source (identified with a source value) and embeds them in the SWF when published. You would place an Embed meta tag over a class variable that is typed as a class that would be used to represent the asset being embedded. Then, to create an instance of that object, you would use new in conjunction with the variable defined as that class.

The EmbedAssets class embeds both an image and a SWF (created in Flash 8) and assigns them to class properties. These class properties are then instantiated and added as children of the main application instance.

package { import flash.display.Sprite; public class EmbedAssets extends Sprite { [Embed(source="images/trophy.png")] private var TrophyImage:Class; [Embed(source="swfs/satdish.swf")] private var SatelliteAnimation:Class; public function EmbedAssets() { addChild(new SatelliteAnimation()); addChild(new TrophyImage()); } } }

As embedded images/animations (or sounds if you required them), these assets are immediately available to the movie when it loads into the player. Alternatively, you can use the Loader class to load external assets at runtime instead of embedding them in the SWF. See the LoadImage class in the source files for an example of this.

Event Handling

If you are familiar with the event model used by V2 components with Flash MX 2004 and Flash 8, you shouldn't have a problem with event handling in ActionScript 3. All events in ActionScript 3 are now handled through the EventDispatcher class. There are no more "on" event methods and no more addListener for objects like Mouse and Stage. Every event handler created will be associated with an event through addEventListener() ; Note: There is no longer a need for the Delegate class used in ActionScript 2 since listener functions maintain their original scope.

Many display objects like Sprite, MovieClip, and TextField inherit from the InteractiveObject class which means they receive events like rollOver, mouseDown, and click among others. For more see the InteractiveObject documentation. Some of these events are a little different than those of ActionScript 1 and 2, but they ultimately allow for more control. See BallToss.as for an example:

package { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; public class BallToss extends Sprite { private var ball:TossableBall; private var lastMouse:Point = new Point(); private var mouseMoved:Point = new Point(); public function BallToss() { var bounds:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); ball = new TossableBall(50, bounds); ball.x = bounds.x + bounds.width/2; ball.y = bounds.y + bounds.height/2; addChild(ball); ball.addEventListener(MouseEvent.MOUSE_DOWN, grabBall); ball.addEventListener(MouseEvent.MOUSE_UP, releaseBall); } private function grabBall(evt:MouseEvent):void { ball.toss(new Point(0,0)); ball.startDrag(); lastMouse = new Point(mouseX, mouseY); addEventListener(Event.ENTER_FRAME, moveBall); moveBall(new Event(Event.ENTER_FRAME)); } private function releaseBall(evt:MouseEvent):void { ball.stopDrag(); ball.toss(mouseMoved); removeEventListener(Event.ENTER_FRAME, moveBall); } private function moveBall(evt:Event):void { var currMouse:Point = new Point(mouseX, mouseY); mouseMoved = currMouse.subtract(lastMouse); lastMouse = currMouse; } } } import flash.display.Sprite; import flash.events.Event; import flash.geom.Point; import flash.geom.Rectangle; class TossableBall extends Sprite { private var bounds:Rectangle; private var vector:Point = new Point(); private var friction:Number = .95; public function TossableBall(size:Number, throwBounds:Rectangle) { bounds = throwBounds; graphics.lineStyle(1); graphics.beginFill(0xFF8000); graphics.drawCircle(0, 0, size/2); addEventListener(Event.ENTER_FRAME, soar); } public function toss(tossVector:Point):void { vector = tossVector; } private function soar(evt:Event):void { x += vector.x; y += vector.y; var shapeBounds:Rectangle = getBounds(parent); if (shapeBounds.left < bounds.left) { vector.x = Math.abs(vector.x); }else if (shapeBounds.right > bounds.right) { vector.x = -Math.abs(vector.x); } if (shapeBounds.top < bounds.top) { vector.y = Math.abs(vector.y); }else if (shapeBounds.bottom > bounds.bottom) { vector.y = -Math.abs(vector.y); } vector.x *= friction; vector.y *= friction; } }

Grab the ball and toss it with your mouse. As an InteractiveObject, the ball can receive mouse events and as a DisplayObject receives the enterFrame event. Note that the event strings for these events are available within the Event and MouseEvent classes as constants.

Was:

MovieClip.onPress = function(){

}

Now:

InteractiveObject.addListener("mouseDown", mouseDownHandler);

...

function mouseDownHandler(){

}

More On ActionScript 3 Class Structure

You may have noticed something new with BallToss.as. The BallToss class defined is within the package code block, but there exists another class, TossableBall that is also defined within that same file outside of that block. In ActionScript 3, you have the option of defining additional helper classes in the same file. These classes would be placed outside the packages block and would only be accessible to classes within that file (internal access). The only class that is accessible outside that file is the main class within package block. The following class, HelperClasses, has 2 classes defined outside its packages block. These classes are accessible to all classes within the file, but not to any other classes outside of the file.

package { import flash.display.Sprite; public class HelperClasses extends Sprite { private var toyBuilder:SantasHelper; public function HelperClasses(){ toyBuilder = new SantasHelper(); } } } class Elf {} class SantasHelper extends Elf {}

The package block can also be used to define functions, not just classes. This would allow you to create functions not associated with any class or instance.

// CallPackagedFunction.as package { import flash.display.Sprite; public class CallPackagedFunction extends Sprite { public function CallPackagedFunction() { PackagedFunction(graphics); } } }

// PackagedFunction.as package { import flash.display.Graphics; public function PackagedFunction(target:Graphics):void { target.lineStyle(0); target.lineTo(100,100); } }

Notice that with the CallPackageFunction class, import was not needed for PackagedFunction. This is true for all classes or functions defined in unnamed packages. Those within actual pacakges would need to be imported using the import statement in order for the compiler to obtain the class being used.

Additional Notes Transitioning From ActionScript 2

There are a lot of changes in ActionScript 3 with the introduction of a brand spanking new virtual machine. Though there are many similarities, ActionScript 3 is not the same ActionScript 2 you are used to. The following will help you get used to some of the changes and avoid common pitfalls:

Member Access: No longer is member access restricted to just public and private (which was essentially protected). ActionScript 3 now supports public , private (truely private), protected , and internal (default).

override: When you wish to extend another class with your own and override methods of the superclass, you are now required to use the override keyword

public class myClip extends MovieClip { override public function play():void { } }

Methods you override cannot be private and they must use the exact method signature. In other words, if the original method had two parameters, so should the method overriding it.

const/final: A new const definition keyword now allows you to create constants, or values that cannot be changed. The new final keyword lets you create classes or methods within classes that cannot be extended or overridden.

final public class myClass { } public const COUNT_VAR:Number = 5; final public function myMethod():void { }

Data Typing: You should now type all members. If a member is allowed any type, then type it using the * special type. Any non-constructor method or function that does not have a return value should be typed as void .

var myNum:Number; var myVar:*;

void: The Void type is now lowercase ( void ). Also, you no longer require void in a function parameter parameter list if a function accepts no arguments

function myFunction():void { }

int/uint: int and uint (unsigned int, or int that cannot be negative) are new data types for whole numbers or numbers that cannot have decimal values. When applicable (such as in loops), these types should be used in favor of the Number type because of their improved efficiency.

Default Values: Some variable types now how default values if one is not provided for them. This includes:

Number: NaN

int: 0

uint: 0

Boolean: false

Variables referenced but not defined or declared (defined without a default value) are seen as undefined. Other declared variables are given a default value of null unless an Object (non-core objects), then they are undefined. Note: Once declared Objects are the only types that can even store the value undefined. Also note, to check for an undeclared Number variable you should use isNaN() .

Parameters/Arguments: Function parameters can now have optional default values. If a parameter is not given a default value, it is seen as being required for that function. If you require an optional number of arguments, you would use the ... (rest) parameter. The ... (rest) parameter creates an array of all optional arguments passed to the function following the last explicit argument value (if defined). The format is three periods followed by the name of the array to hold any additional, optional arguments.

public function main():void { usingOptional(1); // usingOptional(); <- wrong - first parameter required usingRest(1, 2, 3, 4); } private function usingOptional(required:Number, optional:String = "default"):void { trace(required); // 1 trace(optional); // "default" } private function usingRest(required:Number, ... optionalArgs):void { trace(required); // 1 trace(optionalArgs); // [2, 3, 4] }

Enumeration/Iteration/Property checks: A new for each statement has been added to iterate over an objects properties.

for each (variableIterant in object){ }

You can also use the in operator to see if an object contains a certain property. The in operator applies to both instance properties and inherited (prototype) properties.

if ("PI" in Math) { ... // true

To see only properties specific to that object instance and those not in the prototype, use Object.hasOwnProperty("property"); You can also use Object.propertyIsEnumerable("property") to see if the property will reveal itself in enumeration.

Some of this information and more can be found on the ActionScript 3 Learning Tips and ActionScript 3 FAQ pages. Additional information can be found in the ActionScript 3 Language Reference.

Other Resources (in the Source Files)

EasyButton: The EasyButton class is an example of a button that was created from extending the SimpleButton class. Extending SimpleButton is the easiest way to make buttons with the most basic functionality in ActionScript 3. You can add an EasyButton to your class using:

var myButton:EasyButton = new EasyButton("Click Me"); addChild(myButton);

where "Click Me" represents the text displayed by the button. Then you assign an event handler to the button using addEventListener:

myButton.addEventListener("click", myClickMethod);

If you attempt to make your own, more complex button, you would want to use the Sprite class. However, be sure to set its mouseChildren property to false. Otherwise you may experience unexpected mouse event calls.

Output panel: Output.as is a class that creates an output panel on your main stage to be used for tracing and debugging variable values. It works much like trace in the Flash authoring environment only the output panel is in the SWF itself and you will need to call Output.trace() to send values to it (as opposed to simply trace). In order to make use of Output.as, simply call

stage.addChild(new Output(stage));

in the constructor of your application ActionScript class. This will create the Output panel on the main stage and allow you yo trace values to it using Output.trace(); You can clear the output panel using Output.clear(); See SimpleOutputUsage.as for an example using the output panel and some EasyButtons.

SimpleOutputUsage.swf