June 29, 2007

Essential ActionScript 3.0 Now Shipping

Essential ActionScript 3.0 is now available online and in bookstores.

you can order a copy here...

let me know if you write a review somewhere...colin -a-t- moock.org

Posted by moock at 08:45 PM | Comments (28)

June 28, 2007

Chapter 29, Pages 14-18, Essential ActionScript 3.0

Here are pages 14-18 of Chapter 29 of Essential ActionScript 3.0

29. ActionScript and the Flash Authoring Tool

In Chapter 1, we learned that the Flash authoring tool can be used to combine ActionScript code with graphics, animation, and multimedia assets. Now that we have a good understanding of the core ActionScript language, let’s explore the important links between ActionScript and content created in the Flash authoring tool.


Linked Classes for Movie Clip Symbols

From an ActionScript perspective, each Movie Clip symbol instance in a .fla file is represented at runtime by an instance of the Sprite class or one of its subclasses. The class used to represent instances of a specific Movie Clip symbol is known as that symbol’s linked class. A symbol’s linked class can be specified manually, or generated automatically.

To set the linked class for a Movie Clip symbol, we use the Linkage Properties dialog. Note that if any of the following are true, the specified linked class must inherit from flash.display.MovieClip:

* The symbol’s timeline contains any frame scripts.
* The linked class wishes to control instances of the symbol programmatically, using MovieClip methods.
* The symbol’s Stage contains any components with customized parameters and either of the following is true:
a) The customized parameters are not identical on all frames of the timeline. For example, a Button’s label is “OK” on frame 1 and “Submit” on frame 2.
b) The component does not appear on all frames of the timeline. For example, a List with a custom data provider appears on frame 1 but not on frame 2.
* The symbol’s Stage contains any components with customized accessibility properties or Strings Panel content.

Otherwise, the specified linked class need only inherit from flash.display.Sprite.

Here are the steps for specifying the linked class for a Movie Clip symbol.

1. Select the symbol in the .fla file’s Library.
2. Select the pop-up Options menu in the top-right corner of the Library panel, and choose the Linkage option.
3. In the Linkage Properties dialog box, for Linkage, select Export for ActionScript. Note that selecting Export for ActionScript forces the symbol to be included in the compiled .swf file, even if no instance of that symbol is used in the document.
4. In the Linkage Properties dialog box, for Class, enter the fully qualified class name (i.e., the class name combined with the class’s package, if the class resides in a package). The class being linked must be available in either the global classpath or the classpath of the .fla file containing the symbol. When specifying a linked class name in the Linkage Properties dialog, always leave the Base class field at its default value, except when linking more than one symbol to a single superclass, as discussed under “Linking Multiple Symbols to a Single Superclass.”
5. Click OK.

In step 4 of the preceding procedure, if the specified class is not found, the Flash compiler generates a linked class by the specified name automatically. The automatically generated class extends the specified base class.
If no linked class is specified for a given symbol, then the compiler assigns one automatically. If the following conditions are all met, then the automatically assigned linked-class is MovieClip:

* The symbol’s Stage does not contain any named instances.
* The symbol’s timeline has no frame scripts.
* The symbol’s Stage contains no components with customized parameters that vary across frames.
* The symbol’s Stage contains no components with customized accessibility properties or Strings Panel content.

Otherwise, the automatically assigned linked-class is an automatically generated MovieClip subclass.

Once a symbol is linked to a class, manually created instances of that symbol adopt the programmatic behaviors defined by the linked class. Conversely, programmatically created instances of the class adopt the audiovisual content of the linked symbol. Thus the symbol and the class are coupled together—the symbol defines the graphical content, while the class defines the programmatic behavior.

As an example, let’s link our star Movie Clip symbol from the preceding section to a MovieClip subclass, Star. The Star class will randomly change the transparency (alpha value) of each star instance every 100 milliseconds. Here’s the code:

package {
  import flash.display.MovieClip;
  import flash.utils.Timer;
  import flash.events.TimerEvent;
  public class Star extends MovieClip {
    private var timer:Timer;
    public function Star () {
      timer = new Timer(100, 0);
      timer.addEventListener(TimerEvent.TIMER, timerListener);
    private function timerListener (e:TimerEvent):void {
    private function randomFade ():void {
      // Set alpha to a random floating-point value from 0 up to (but
      // not including) 1. The instance variable alpha is inherited from
      // the DisplayObject class (which is ancestor of MovieClip).
      alpha = Math.random();
    // Provide a means of stopping the timer. As discussed in section
    // "Deactivating Objects" in Chapter 14,
    // external code should use this method before removing a star instance
    // from the program.
    public function dispose ():void {

To link the Star class to the star Movie Clip symbol, we follow these steps:

1. Save the file containing the star symbol as sky.fla.
2. Save the Star class in a text file named Star.as, in the same folder as sky.fla.
3. Select the star symbol in sky.fla’s Library.
4. Select the pop-up Options menu in the top-right corner of the Library panel, and choose the Linkage option.
5. In the Linkage Properties dialog, for Linkage, select Export for ActionScript.
6. In the Linkage Properties dialog, for Class, enter Star.
7. Click OK.

To create instances of the star symbol in the Flash authoring tool, we drag the symbol name from the Library to the Stage of the main timeline (or to any other symbol’s Stage—but, in this case, there are no other symbols in the document).

Once the star symbol instances are on the main timeline, we can export sky.swf from sky.fla, and watch the each star’s twinkling motion (defined by the star symbol) and fading effect (defined by the Star class).

Now that we know how to manually create instances of Movie Clip symbols, let’s examine how to access and control them.

Posted by moock at 09:42 PM

June 27, 2007

checking if one class inherits from another

in ActionScript 3.0 you can list all of the ancestors of a class like this:

var theClass:Class = Sprite;
var superName:String;
while (superName != "Object") {
  // Retrieve the name of theClass's superclass
  superName = getQualifiedSuperclassName(theClass);
  // Retrieve a reference to theClass's superclass
  theClass = Class(getDefinitionByName(superName));



here's a generalized function that uses the same basic technique to check whether one class inherits from another:

import flash.utils.*;
  public function inheritsFrom (descendant:Class, 
                                ancestor:Class):Boolean { 
  var superName:String;
  var ancestorClassName:String = getQualifiedClassName(ancestor);
  while (superName != "Object") {
    superName = getQualifiedSuperclassName(descendant);
    if (superName == ancestorClassName) {
      return true;
    descendant = Class(getDefinitionByName(superName));
  return false;


trace("Does Sprite inherit from DisplayObject?");
// Displays: yes
trace(inheritsFrom(Sprite, DisplayObject) ? "yes" : "no");
Posted by moock at 05:14 PM

June 15, 2007

Chapter 28, Pages 1-5, Essential ActionScript 3.0

Here are the first 5 pages of Chapter 28 of Essential ActionScript 3.0

28. Loading External Display Assets

In ActionScript, there are three ways to programmatically add an external display asset to an application:

* Use the flash.display.Loader class to load the asset at runtime
* Use the flash.net.Socket class in combination with the Loader class’s instance method loadBytes() to load the asset at runtime over a direct TCP/IP socket
* Use the [Embed] metadata tag to include the asset from the local file system at compile-time

The Loader and Socket classes are built-in to the Flash runtime API, while the [Embed] metadata tag requires the Flex framework. All three approaches support the following display asset formats:

* SWF (compiled Flash applications)
* JPEG, GIF, or PNG (bitmap images)

Additionally, the [Embed] metadata tag supports SVG-formatted display assets.

The Loader class replaces the following ActionScript 2.0 loading tools:
* MovieClipLoader class
* loadMovie() and loadMovieNum() global functions
* MovieClip class’s instance methods loadMovie() and loadMovieNum()

In this chapter, we’ll learn how to use Loader, Socket, and [Embed] to load external display assets. For information on loading fonts, see Chapter 27. For information on loading XML, see Chapter 18. For information on loading other non-display assets, such as variables, binary data, or sound, see the URLLoader, URLStream, and Sound class entries in Adobe’s ActionScript Language Reference.

Using Loader to Load Display Assets at Runtime

The Loader class loads an external display asset at runtime. The asset can be retrieved over HTTP or from the local file system. There are three basic steps to using the Loader class:

* Create the flash.display.Loader instance.
* Create a flash.net.URLRequest instance that specifies the asset’s location.
* Pass the URLRequest instance to the Loader instance’s load() method.

Over the next few sections we’ll create an example class, SunsetViewer, that demonstrates the preceding steps in detail. Our example class will load a single bitmap image, sunset.jpg. Once we’re comfortable with the basics of loading an asset, we’ll then examine how to monitor the progress of a load operation using the flash.display.LoaderInfo class. Finally, we’ll consider the code required to access the loaded asset and add it to the display list.

Load operations are subject to Flash Player security limitations. For complete coverage, see Chapter 19.

In our SunsetViewer example, we’ll presume that the application .swf file, SunsetViewer.swf, will be posted to a web site in the same directory as the image we’re loading sunset.jpg.

Creating the Loader Instance

As we just learned, the first step in loading any display asset at runtime using Loader is creating a Loader instance. The Loader instance manages the load operation and provides access to the loaded asset. We’ll create our Loader instance in SunsetViewer’s constructor method and assign it to an instance variable named loader, as shown in Example 28-1:

Example 28-1. Creating the Loader instance

package {
  import flash.display.*;
  public class SunsetViewer extends Sprite {
    private var loader:Loader;
    public function SunsetViewer () {
      loader = new Loader();  // Create the Loader instance

Specifying the Asset’s Location

To load an external display asset using a Loader instance, we must specify the asset’s location with a flash.net.URLRequest object. Each individual URLRequest object describes the location of a single external resource, either on the network or the local file system. To create a URLRequest object that specifies an asset’s location, use the following general code, which assigns the asset’s location to the instance variable url:

var urlRequest:URLRequest = new URLRequest();
urlRequest.url = "theAssetURL";

Alternatively, the asset’s location can be passed to the URLRequest constructor, as in:

var url:URLRequest = new URLRequest("theAssetURL");

In both cases, theAssetURL is a string containing a standard URL. For example,

new URLRequest("http://www.example.com/image.jpg");

The set of network protocols allowed in the theAssetURL is dependent on the operating system. For example, http://, https://, and ftp:// are all supported by Windows, Macintosh, and UNIX, but a request for Windows help content (ms-its:) might be supported on Windows only. For security reasons, Flash Player might also block some protocols. However, Adobe does not currently publish a list of blocked protocols. Furthermore, ActionScript does not generate any security error messages relating specifically to protocol blocking. Hence, when working with unusual protocols, be aware that load operations involving some unusual protocols may fail silently.

In addition to specifying a URL, each URLRequest object can also provide supplementary information for requesting a resource over HTTP. To specify an HTTP request’s header, method, POST data, query string, and MIME content type, simply set the appropriate URLRequest variables, as documented in Adobe’s ActionScript Language Reference. For example, to specify an HTTP request’s headers, set the URLRequest class’s instance variable, requestHeaders.
An asset’s location can be specified as an absolute or relative URL. However, note that Flash Player’s system for resolving relative URLs varies depending on how Flash Player is launched:

* If Flash Player is launched in order to display a .swf file embedded in a web page via the <OBJECT> or <EMBED> tag, then all relative URLs are resolved in relation to that web page—not in relation to any .swf file. Further, if the web page was opened locally, relative URLs are resolved locally; if the web page was opened over the Internet, relative URLs are resolved over the Internet.

* If Flash Player is launched as a standalone application or by browsing directly to a .swf file in a Flash-enabled web browser, then all relative URLs are resolved in relation to the first .swf file opened by Flash Player—known as the stage owner. Further, if the stage owner was opened locally, relative URLs are resolved locally; if the stage owner was opened over the Internet, relative URLs are resolved over the Internet.

Even if the first .swf file opened by Flash Player is removed from the stage, it is still considered the stage owner, and still governs relative-URL resolution.
Let’s consider a relative-URL example that demonstrates the preceding two relative-URL-resolution systems. Suppose we embed an application, SunsetViewer.swf, on a web page, SunsetViewer.html, and we store those two files in the following separate directories:


Suppose also that from SunsetViewer.swf we want to load an image, sunset.jpg, which also resides in the /assets/ directory:


If we expect the user to view SunsetViewer.swf by browsing to the web page SunsetViewer.html, then we must compose our relative URL in relation to the web page, as follows:

new URLRequest("assets/sunset.jpg");

But if we expect the user to browse directly to SunsetViewer.swf, then we would compose our relative URL in relation to the .swf file, not the web page, as follows:

new URLRequest("sunset.jpg");

When distributing content for playback in Flash Player, compose all relative URLs according to how you expect your users to launch Flash Player.
Even when a .swf file loads another .swf file that, itself, loads external assets, relative URLs are still resolved in relation to either the stage owner (in the case of a direct launch) or the web page containing the embedded Flash Player (in the case of a web page launch). For example, suppose we open a hypothetical application, SlideShow.swf, directly in Flash Player. Next suppose SlideShow.swf loads the preceding SunsetViewer.swf example. In such a case, all relative URLs in SunsetViewer.swf would have to be composed relative to SlideShow.swf (notice: not relative to SunsetViewer.swf!). Similarly, if SlideShow.swf were viewed via a web page, then all relative URLs in SunsetViewer.swf would have to be composed relative to that web page.

You can completely avoid the issue of varying-relative-URL-resolution by storing all .html files, .swf files, and external-display-asset files in the same directory.

Now let’s return to our example SunsetViewer class. Earlier, in Example 28-1 we created a Loader instance. Example 28-2 updates the SunsetViewer class, adding code that creates a request for the relative URL "sunset.jpg". As mentioned earlier, for the sake of our example, we’ll assume that sunset.jpg is stored in the same directory as SunsetViewer.swf, thus avoiding any relative-URL complexity.

Example 28-2. Specifying the asset’s location

package {
  import flash.display.*;
  import flash.net.URLRequest;  // Import the URLRequest class
  public class SunsetViewer extends Sprite {
    private var loader:Loader;
    public function SunsetViewer () {
      loader = new Loader();
      // Specify asset location as "sunset.jpg"
      var urlRequest:URLRequest = new URLRequest("sunset.jpg");

Now that we’ve specified the location of sunset.jpg, let’s actually load it.

[52 more pages...]

Posted by moock at 05:56 PM

June 14, 2007

Chapter 27, Paragraphs 1-9, Essential ActionScript 3.0

Here are the first 9 paragraphs of Chapter 27 of Essential ActionScript 3.0

27. Text Display and Input

Flash Player offers an extensive, sophisticated API for working with text. In this chapter we’ll look at some of its key features: creating and displaying text, formatting text, and handling text input.

The information presented in this chapter applies specifically to Flash Player (both the browser add-on and standalone versions), but is also generally applicable to any Flash runtime that supports full-featured text display and input, such as Adobe AIR. Note, however, that unlike Flash Player, Adobe AIR provides full-featured HTML and CSS support, analogous to that found in Web browsers such as Microsoft Internet Explorer and Mozilla Firefox. When working with other Flash runtimes, be sure to consult the appropriate documentation for information on text support.

The centerpiece of Flash Player’s text API is the TextField class, which provides control over text displayed on screen.

In this book (and in most ActionScript documentation), the term “text field,” refers, in a general sense, to a given text field on screen and its corresponding ActionScript TextField instance. Meanwhile, the phrase “a TextField object” refers more specifically to the ActionScript object that controls a text field.

Creating and Displaying Text

To display text with ActionScript, we first create a TextField object. The TextField object represents a rectangular text container that can be displayed on screen and filled with formatted text via code or user input. For example, the following code creates a TextField object and assigns it to the variable t:

var t:TextField = new TextField();

After creating a TextField object, we use the TextField class’s instance variable text to specify the text to display. For example, the following code specifies “Hello world” as the text to display in t:

t.text = "Hello world";

Finally, to display the text field on screen, we pass the TextField object to the addChild() or addChildAt() method of any DisplayObjectContainer that is currently on the display list. For example, assuming someContainer is on the display list, the following code causes the text field t to appear on screen:


Example 27-1 shows the preceding code in the context of a demonstration class, HelloWorld. In the example, notice that we import the TextField class (along with all classes in the flash.text package) before using it.

Example 27-1. Displaying text

package {
  import flash.display.*;  
  import flash.text.*;  // Import TextField
  public class HelloWorld extends Sprite {
    public function HelloWorld () {
      // Create a TextField object
      var t:TextField = new TextField();
      // Specify the text to display
      t.text = "Hello world";
      // Add the TextField object to the display list
Posted by moock at 08:00 PM

June 06, 2007

Chapter 26, Paragraphs 1-8, Essential ActionScript 3.0

Here are the first 8 paragraphs of Chapter 26 of Essential ActionScript 3.0

26. Bitmap Programming

In programming terms, a bitmap image is an image stored in bitmap data format. The bitmap data format treats an image as a rectangular grid of pixels, where each pixel in the grid is assigned a number that indicates its color. For example, in bitmap data format, an image with a width and height of 16 pixels would be stored as a list of 256 numbers, each indicating a specific color. Figure 26-1 demonstrates, showing a 16x16-pixel image magnified to reveal its individual pixels. The right-hand side of the figure shows the grid position and color values of three sample pixels in the image. Notice that positions on the grid are zero-based, so the top-left pixel’s coordinate is (0, 0), while the bottom-right pixel’s coordinate is (15, 15).

Figure 26-1. An example bitmap image

In this chapter, we’ll explore a sampling of common bitmap programming techniques. Bear in mind, however, that exhaustive coverage of bitmap programming in ActionScript could well fill a book of its own. For further study, consult Adobe’s ActionScript Language Reference.

The BitmapData and Bitmap Classes

In ActionScript, the BitmapData class represents bitmap-formatted image data such as that in Figure 26-1. Each BitmapData instance contains a list of pixel color-values, and instance variables width and height that governs how those pixels are arranged on screen. Using the BitmapData class, we can create the data for a completely new bitmap image, or examine and modify the data of any existing bitmap image, including externally loaded bitmap images.

The BitmapData class provides a wide range of tools for setting and retrieving the color value of a given pixel or group of pixels, and for producing common graphic effects such as blur or drop shadow. As we’ll see later, the BitmapData class can even be used to create animated effects and to perform bitmap-based collision detection. To use most of BitmapData’s tools we must understand the format ActionScript uses to describe a pixel’s color value, discussed in the next section.

As the name suggests, a BitmapData object is not, itself, an image—it is only the bitmap-formatted data representing an image. To create an actual on-screen image based on the information in a BitmapData object, we must pair that object with an instance of the Bitmap class, as described later under “Creating a New Bitmap Image.” The Bitmap class is a DisplayObject descendant that wraps a BitmapData object for on screen display.

When working with a bitmap image, we use the Bitmap class to manipulate the image as a display object, and the BitmapData class to manipulate the image’s underlying pixel data.

By separating image display (Bitmap) from data storage (BitmapData), ActionScript’s bitmap architecture lets many different Bitmap objects simultaneously display the same BitmapData object, each with its own display characteristics (i.e., different scale, rotation, cropping, filters, transforms, and transparency).

Before we learn how to create a new bitmap image, let’s take a quick look at how colors are represented in ActionScript.

Posted by moock at 09:11 PM

June 05, 2007

Chapter 25, Paragraphs 1-5, Essential ActionScript 3.0

Here are the first 5 paragraphs of Chapter 25 of Essential ActionScript 3.0

25. Drawing with Vectors

In ActionsScript, primitive vectors lines and shapes are drawn via the Graphics class. However, the Graphics class is never instantiated directly; instead, each ActionScript class that supports programmatic vector drawing creates a Graphics instance automatically and provides access to it via the instance variable graphics. The display classes that support vector drawing are Sprite, MovieClip, and Shape.

Shape objects consume less memory than Sprite and MovieClip objects. Hence, to conserve memory, vector content should be drawn in Shape objects whenever the containment and interactive capabilities of the Sprite and MovieClip classes are not required.

Graphics Class Overview

As shown in Table 25-1, the Graphics class’s drawing tools can be broken down into five general categories: drawing lines, drawing shapes (also known as fills), defining line styles, moving the drawing pen, and removing graphics.

Table 25-1. Graphics class overview

Drawing lines
curveTo(), lineTo()

Drawing shapes
beginBitmapFill(), beginFill(), beginGradientFill(), drawCircle(), drawEllipse(), drawRect(), drawRoundRect(), drawRoundRectComplex(), endFill()

Defining line styles
lineGradientStyle(), lineStyle()

Moving the drawing pen

Removing graphics

Conceptually, lines and curves are drawn in ActionScript by a theoretical “drawing pen.” For all new Sprite, MovieClip, and Shape objects, the pen starts out at position (0,0). As lines and curves are drawn (via lineTo() and curveTo()), the pen moves around the object’s coordinate space, resting at the end point of the last line or curve drawn. The pen’s current position always indicates the starting point of the next line or curve to be drawn. To arbitrarily set the starting point of a line or curve, we use the moveTo() method, which “picks up” the drawing pen and moves it to a new position without drawing a line to the specified point.

Posted by moock at 10:24 PM