Chapter 19. Where Did It Go?

Introduction

Migrating from ActionScript 2.0 to ActionScript 3.0 is as much a matter of following subtle changes in the development of the language as learning new features. In many cases, all you’ll need to do to upgrade a script, you just have to change a class name or, perhaps, change from a method to a property. These kinds of changes are typically easy to identify because you need minor adjustments. In other cases, however, you may find yourself searching for missing functionality. Like looking up an unfamiliar word in the dictionary, you need a place to start.

What’s Included

This chapter is essentially a cross-reference to material covered elsewhere in this book, but also includes additional material not otherwise discussed. The primary goal is to help you find something you used in ActionScript 2.0 but appears to be missing or significantly changed in ActionScript 3.0.

Itemizing every change introduced by ActionScript 3.0 is beyond the scope of this book. However, you can find a concise, table-based guide called “ActionScript 2.0 Migration” in the Help system by searching for “migration” or by looking online at http://livedocs.adobe.com/flex/2/langref/migration.html. While this table doesn’t include examples, it does point you to the correct new Help entry in ActionScript 3.0 syntax, if one exists.

When you know specifically what to look for, and in which package or class to look, the Help table is probably the best place to start. However, you can use this chapter as a supplemental tool to preplan migration efforts by identifying known issues that affect a broader category such as asset display or sound, for example. Loosely organizing topics into larger categories this way is particularly helpful when changes affect more than one property, method, or event, and even span multiple classes.

In all cases, the code snippets are not fully realized scripts but rather syntax examples to point you in the right direction.

What’s Not Included

A few things won’t be addressed here, so that the chapter can cover as much as possible of what you’re most likely to run into during a migration session. So, this chapter doesn’t cover:

Syntax deprecated in ActionScript 2.0

Some ActionScript syntax introduced with version 1.0 of the language was replaced with better, or more standards-compliant, syntax in ActionScript 2.0. Examples include operators like gt (string greater than), <> (mathematical not equal to), and or (logical or), global functions like tellTarget() (for object addressing prior to the use of dot-syntax), and object properties like __proto__ (an early OOP technique).

Features entirely new in ActionScript 3.0

This chapter is primarily designed to help you find ActionScript 3.0 solutions to problems you’re used to solving with ActionScript 2.0. New material’s included here, but the focus is on migration rather than taking advantage of features introduced for the first time with ActionScript 3.0. Much of the entirely new material is discussed in earlier chapters of this book.

Repetition of consistent changes across multiple categories or topics

One of the concepts stressed throughout this book is the consistency that version 3.0 of ActionScript brings to the language. Some changes, such as the new event architecture, apply to many classes and aren’t repeated herein.

Code Comparisons

Half the battle when upgrading existing projects is knowing how to change older code. The remainder of this chapter identifies select migration issues and compares ActionScript 2.0 and 3.0 syntax.

Language Fundamentals

Several very basic changes introduced in ActionScript 3.0 affect the way a script is structured. Ranging from default values to scope issues, these language fundamentals are not category-specific.

Examining and using default values

ActionScript 2.0: Checking variables for initial values often involves a comparison against null or undefined.

var userNum:Number;
if (userNum == undefined) {
userNum = 1;
}

ActionScript 3.0: A value of undefined can be used only for untyped variables. Every data type now has a default value, as seen in Table 19-1.

Table 19-1. Data type default values

Data type

Default value

int

0

uint

0

Number

NaN

Object

null

String

null

Boolean

false

untyped (*)

undefined

all other (including user-defined classes)

null

Equality can be used for most default value validations, but the isNaN() method should be used for the Number data type.

var userNum:Number;
if (isNaN(userNum)) {
    userNum = 1;
}

Additionally, ActionScript 3.0 allows the assignment of default values for function parameters. See Chapter 18, for more information about default values.

Referencing objects by evaluated expression

ActionScript 2.0: You can dynamically build a reference to an object using the eval() to evaluate an expression. For example, you can refer to

trace(eval("this.myClip" + i));

ActionScript 3.0: The eval() method is gone. Although using scope bracket syntax, such as this["myClip" + i], is still possible, using getChildByName() is the recommended practice.

trace(this.getChildByName("myClip" + i));

See 13.5 Finding a Display Object for more information about finding a display object by name.

Creating global variables and functions

ActionScript 2.0: The declaration _global lets you create global variables and functions.

_global.userName = "David Thomas";
_global.pereUbu = function ():Void {
    getURL("http://ubuprojex.net/");
}
trace(userName);
pereUbu();

ActionScript 3.0: Global variables and functions have been removed. Use a static class member, a Singleton (a class that allows only one instance), or, for variables accessible to an entire display list (which isn’t really global), you can rely on the root reference. See the next entry. The following snippet is an example of the static class member approach. The Global class allows the storage of variables in a dynamically populated object.

Global.as

package {
    public class Global {
        public static var vars:Object = {};
    }
}

Elsewhere, in another class or frame script, you can store variables as object properties, including functions. To demonstrate, the last three lines of this snippet trigger the global function after a one-second delay.

import Global;
Global.vars.userName = "David Thomas";
Global.vars.pereUbu = function():void {
    navigateToURL(new URLRequest("http://ubuprojex.net/"));
}

trace(Global.vars.userName);
var tmr:Timer = new Timer(1000, 1);
tmr.addEventListener(TimerEvent.TIMER, Global.vars.pereUbu, false, 0, true);
tmr.start();

Be aware that, like ActionScript 2.0 global variables, this simple approach doesn’t use type checking for variable values.

Accessing the root of a SWF file

ActionScript 2.0: The _root is the host SWF file played by Flash Player regardless of whether it is standalone (which makes it the _root) or loaded into another SWF file (which makes the parent SWF file the _root). This makes addressing a movie clip, or storing a variable, unpredictable. The _lockroot property helps work around this problem by allowing _root references to remain SWF-file-specific. If _lockroot is set to true, when a SWF file is loaded into a parent SWF file, _root in the loadee SWF file is still the main timeline of the loadee, and _root in the loader SWF file is still the main timeline of the loader.

_root.mc._x = 100;
_root.userName = "Kramer";

ActionScript 3.0: The new root is the senior most display object in the current scope, and functions somewhat as if _lockroot is true in ActionScript 2.0. If you choose to use root as a variable repository, then you must first cast it as MovieClip so you can dynamically assign properties (variables).

MovieClip(root).mc.x = 100;
MovieClip(root).userName = "Kramer";

See 13.8 Working with Parents of a Display Object and 13.9 Casting a Display Object from One Type to Another, as well as Chapter 18, for more information about dynamic versus sealed classes.

Using delegates

ActionScript 2.0: The Delegate class is used to link scope with the execution of a function or method.

_tempSound.onLoad = Delegate.create(this, onSoundPreloaded);

ActionScript 3.0: This is now unnecessary due ActionScript 3.0’s method closure. See the Method Closures of Chapter 18 for more information.

Display

Controlling visual elements in Flash is entirely different in ActionScript 3.0, so you see many changes from previous versions, large and small. For an in-depth look at display objects and the display list, see Chapter 13.

Accessing the Stage

ActionScript 2.0: The Stage is a top-level class and you can get to it from anywhere.

trace(Stage.width);

ActionScript 3.0: You can access the Stage only through a display object that’s part of the display list. This example also demonstrates a subtle difference in the name of the property to specify width, changing from width in ActionScript 2.0 to stageWidth.

var sp:Sprite = new Sprite();
addChild(sp);
trace(sp.stage.stageWidth);

See 13.11 Referencing the Stage Through a Display Object for more information about accessing the stage through a display object.

Accessing a parent

ActionScript 2.0: The _parent property identifies the parent of a symbol instance or loaded SWF file.

this._parent.gotoAndStop(2);

ActionScript 3.0: The parent property works the same way, but ActionScript 3.0 has many more display object types, so the compiler sometimes needs to be told that the requested property or method of a parent is legal. For example, a parent could be a sprite, rather than a movie clip, in which case frame navigation actions wouldn’t apply. Telling the compiler that the parent’s a movie clip by casting it as such eliminates any possible confusion.

MovieClip(this.parent).gotoAndStop(2);

See 13.9 Casting a Display Object from One Type to Another for more information about accessing a parent of a display object and casting from one data type to another.

Creating an empty movie clip

ActionScript 2.0: Creating an empty movie clip requires the createEmptyMovieClip() method, a new instance name, and a level. The clip is automatically displayed.

var mc:MovieClip = this.createEmptyMovieClip("clip", 1);

ActionScript 3.0: You create all display objects using the new keyword and appropriate class, and you must add them to the display list to be visible.

var mc:MovieClip = new MovieClip();
addChild(mc);

See 13.2 Creating a New Display Object for more information about creating a new movie clip.

Adding a library movie clip to the stage

ActionScript 2.0: Adding an existing movie clip to the stage requires the attachMovie() method, the symbol’s linkage name, a new instance name, and a level. The clip is automatically displayed.

var mc:MovieClip = this.attachMovie("Help","helpHeadline",2);

ActionScript 3.0: You create all display objects using the new keyword and appropriate class. Instead of using a linkage name, you use a symbol’s class name, and instantiate the clip just like an empty movie clip. You can type the reference variable to the class type if it helps clarify your intent, but you need not write a custom class for this feature to work. You can also type to MovieClip, for example, if you prefer (as seen here). See Creating a bitmap” for more information. You must add the instance to the display list to make it visible.

var mc:MovieClip = new Help();
addChild(mc);

See 13.2 Creating a New Display Object for more information about adding a library element to the display list.

Duplicating a movie clip

ActionScript 2.0: You can duplicate a movie clip instance using the duplicateMovieClip() method, a reference to the original clip, a new instance name, and a new level.

duplicateMovieClip(mc, "mc2", 2);

ActionScript 3.0: This functionality has been removed. The recommended approach is to use new to create another instance of the relevant movie clip, but this will not inherit any of the original movie clip’s attributes. To accomplish something similar in ActionScript 3.0, you must create a custom clone method that analyzes the original and attempts to apply all of its attributes to the copy.

Creating a bitmap

ActionScript 2.0: Create a BitmapData object, and attach it to a movie clip using the attachBitmap() method, specifying a level.

import flash.display.BitmapData;
var bmpMC:MovieClip = this.createEmptyMovieClip("bmpContainer", 1);
var bmpData:BitmapData = new BitmapData(200, 200);
bmpMC.attachBitmap(bmpData, 2);

ActionScript 3.0: Create a Bitmap instance and add it to the display list.

var bmp:Bitmap = new Bitmap();
addChild(bmp);

Adding a library bitmap to the stage

ActionScript 2.0: This process is similar to the ActionScript 2.0 method for creating a bitmap but, rather than creating a new BitmapData instance, you use loadBitmap() method and the library bitmap’s linkage name to create an instance from the bitmap.

var bmpD:BitmapData = BitmapData.loadBitmap("Logo");
var mc:MovieClip = this.createEmptyMovieClip("mc", 2);
mc.attachBitmap(bmpD, 2);

ActionScript 3.0: Specify a linkage class for the bitmap in the library, and create a new instance of the class. You must add it to the display list for it to be visible. Here again, you can type to the custom class, or to the base class. In this example, the custom class is used. See Adding a library movie clip to the stage for more information.

var logoBmp:Logo = new Logo(100,100);
var bmp:Bitmap = new Bitmap(logoBmp);
addChild(bmp);

Checking the level of a display object

ActionScript 2.0: You can get the level of a symbol instance by using the _level property.

var mc:MovieClip = this.createEmptyMovieClip("clip", this.getNextHighestDepth());
trace(mc._level);
//_level0

ActionScript 3.0: The _level property has been removed. Use the getChildIndex() method of a display object container instead.

var mc:MovieClip = new MovieClip();
addChild(mc);
trace(getChildIndex(mc));

Getting the highest unused depth

ActionScript 2.0: Use the getNextHighestDepth() method (or the DepthManager class when using version 2.0 components).

var mc:MovieClip = this.createEmptyMovieClip("mc", this.getNextHighestDepth());

ActionScript 3.0: Depth management is automatic and the highest level is automatically used when adding to the display list.

var mc:MovieClip = new MovieClip();
addChild(mc);

See 13.3 Adding a Display Object to the Display List for more information about adding a display object to the display list using the highest available depth.

Swapping display object depths

ActionScript 2.0: Use the swapDepths() method.

mc1.swapDepths(mc2);

ActionScript 3.0: For corresponding functionality, use the swapChildren() method to swap known display objects, or the swapChildrenAt() method to swap the children in two depths. However, you can also use the addChild() method to place a child at the top of the display list, or addChildAt() method to place it at a specific level. All children above move up a level, accordingly.

swapChildren(mc1, mc2);
swapChildrenAt(0, 1);

See 13.4 Specifying the Depth of a Display Object for more information about specifying the depth of a display object.

Accessing a display object by name

ActionScript 2.0: You can access a symbol instance using a programmatically created instance name instead of a variable reference.

this.createEmptyMovieClip("clip", 1);
trace(clip._x);
//0

ActionScript 3.0: This option’s no longer a part of the display object creation process, so you can’t use a programmatically created instance name to access display objects.

var mc:MovieClip = new MovieClip();
addChild(mc);
mc.name = "clip";
trace(clip.x)
//error

Instead, use the getChildByName() method.

trace(getChildByName("clip"));
//[object MovieClip]

Actually, this method’s consistent with ActionScript 2.0. The only difference is that you can assign an instance name during creation. Even in ActionScript 2.0, you can’t access a movie clip through the value of its name property.

var mc:MovieClip = this.createEmptyMovieClip("clip", 1);
mc.name = "clip2";
trace(clip2._x);
//undefined
trace(clip._x);
//0

See 13.5 Finding a Display Object for more information about finding a display object by name.

Removing a display object

ActionScript 2.0: Use the removeMovieClip() method to remove a movie clip or button instance.

removeMovieClip(mc);

ActionScript 3.0: Use the removeChild() method to remove any display object.

removeChild(mc);

See 13.6 Removing a Display Object from the Display List for more information about removing a display object from the display list.

Using the drawing API

ActionScript 2.0: Drawing API methods are part of the MovieClip class, letting you draw into movie clips without reference to any other classes.

mc.lineStyle(1, 0x000000);
mc.lineTo(10, 10);

ActionScript 3.0: Drawing API methods have been moved to the Graphics class, and you can access them through the graphics property in shapes, sprites, and movie clips.

mc.graphics.lineStyle(1, 0x000000);
mc.graphics.lineTo(10, 10);

See all of Chapter 12, for more information about using the Graphics class.

Checking for display object collisions

ActionScript 2.0: Use the hitTest() method to check for a collision with another symbol instance (the first line) or point (the second line).

trace(mc.hitTest(mc2));
trace(mc.hitTest(100, 100));

ActionScript 3.0: Use the hitTestObject() method or hitTestPoint() method to check for a collision with a display object or point, respectively.

trace(mc.hitTestObject(mc2));
trace(mc.hitTestPoint(100, 100));

Assigning a mask to movie clip

ActionScript 2.0: Use the setMask() method to assign one movie clip as a mask for another movie clip.

mc.setMask(mc2);

ActionScript 3.0: The process is the same as in ActionScript 2.0 but mask is a property.

mc.mask = mc2;

See 12.11 Using a Drawn Shape as a Dynamic Mask for more information about assigning a mask to a display object.

Events

Like the display architecture, the ActionScript 3.0 event model differs greatly from previous versions. From handling built-in events to dispatching custom events, significant changes present new migration challenges.

Using event handlers

ActionScript 2.0: Event handlers commonly take the form of onEventName() and are methods of the object meant to react to the event. The following is an example of a button frame event:

helpBtn.onRelease = buttonRelease;
function buttonRelease():Void {
    trace("button action here");
}

ActionScript 3.0: Event listeners now handle all events exclusively.

helpBtn.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
function onClick(evt:MouseEvent):void {
    trace("button action here");
}

See all of Chapter 14, for extensive discussions about events, as well as Chapter 18, for information about components and a comparison of event listener use in ActionScript 2.0 and 3.0.

Adding and removing listeners

ActionScript 2.0: Some classes, including Key, Mouse, MovieClipLoader, Stage, TextField, and Selection use the addListener() method to register event listeners, and the removeListener() method to remove listeners.

var txtListener:Object = new Object();
txtListener.onChanged = function(tf:TextField):Void {
    trace(tf.text);
    tf.removeListener(txtListener);
};
txtFld.addListener(txtListener);

ActionScript 3.0: All listeners are registered using the addEventListener() method, and removed using the removeEventListener() method.

txtFld.addEventListener(Event.CHANGE, onChange);
function onChange(evt:Event):void {
    trace(evt.target.text);
    evt.target.removeEventListener(Event.CHANGE, onChange);
};

See all of Chapter 14 for extensive discussions about events, as well as information about components and a comparison of event listener use in ActionScript 2.0 and 3.0.

Enabling event dispatching

ActionScript 2.0: You must prepare an object for event broadcasting.

AsBroadcaster.initialize(obj);

ActionScript 3.0: You no longer need to prepare an object for event dispatching. All classes that extend EventDispatcher, including all display objects, can automatically dispatch events.

Dispatching events

ActionScript 2.0: Use the broadcastMessage() method of AsBroadcaster to broadcast events.

obj.broadcastMessage("edited");

ActionScript 3.0: Use the dispatchEvent() method of the EventDispatcher class to dispatch events.

dispatchEvent(new Event("edited"));

See 14.12 Dispatching Your Own Events for more information about dispatching custom events.

Trapping a mouse up event outside a display object’s boundaries

ActionScript 2.0: Use the onReleaseOutside event.

mc.onReleaseOutside = function ():Void {
    trace("onReleaseOutside called");
};

ActionScript 3.0: This event has been removed from ActionScript 3.0. Attach an additional mouse up event listener to the stage to simulate a mouse up outside the display object. See 14.6 Simulating a Mouse Up Outside Event for more information about simulating a mouse up outside event.

mc.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
function onUp(evt:MouseEvent):void {
    trace("mouse up behavior");
}
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);

Text

Several changes have been made to the TextField, TextFormat, and related classes, affecting everything from creating text fields to triggering functions from hyperlinks.

Creating a new text field

ActionScript 2.0: Use the createTextField() method, supplying an instance name, level, x and y coordinates, and width and height. The instance is automatically added to the stage.

var txtFld:TextField = this.createTextField("txt", 1, 0, 0, 100, 100);

ActionScript 3.0: Use the new keyword and TextField constructor, and add it the display list. The level is determined automatically, and the default values of x:0, y:0, width:100, and height:100 are used. Alternatively, each property can be set individually.

var txtFld:TextField = new TextField();
addChild(txtFld);

See 15.1 Creating a Text Field for more information about creating a text field.

Populating a text field with plain text

ActionScript 2.0: Populate the first string using the equal (=) operator and add to that text using the plus-equal (+=) compound operator.

txtFld.text = "start";
txtFld.text += "continue";

ActionScript 3.0: Populate the first string using the equal (=) operator and add to that text using the appendText() method for better performance. See 15.5 Populating a Text Field for more information.

txtFld.text = "start";
txtFld.appendText("continue");

Populating a text field with HTML

ActionScript 2.0: Use the same techniques for populating a field with plain text, but set the html property to true and use the htmlText property instead of the text property to assign the text.

txtFld.html = true;
txtFld.htmlText = "<b>start</b>";
txtFld.htmlText += "continue";

ActionScript 3.0: The same process is used for ActionScript 3.0, but the html property is unnecessary, and it’s been removed. Note that, unlike when working with plain text, there’s no append method, and you use the plus-equal (+=) compound operator.

txtFld.htmlText = "<b>start</b>";
txtFld.htmlText += "continue";

See 15.10 Formatting Text Using HTML for more information about using HTML in a text field.

Setting a default text format

ActionScript 2.0: Use the setNewTextFormat() method to assign a text format before adding text to the field.

txtFld.setNewTextFormat(txtFrmt);
txtFld.text = "Rex Stout";

ActionScript 3.0: The same process is used for ActionScript 3.0, but defaultTextFormat is a property.

txtFld.defaultTextFormat = txtFrmt;
txtFld.text = "Rex Stout";

See 15.9 Formatting Text Using TextFormat for more information about formatting text with a TextFormat instance.

Using a text field as a variable

ActionScript 2.0: You can assign dynamic and input text fields variable names in the Property inspector. The field then displays the value of the variable throughout its use.

ActionScript 3.0: This feature has been removed.

Scrolling a text field

ActionScript 2.0: Assign to the scroll property a number of the line to which you wish to scroll. Using the maxScroll property for this value scrolls the field to the end of the text.

txtFld.scroll = txtFld.maxscroll;

Horizontal scrolling is also possible, using hscroll and maxhscroll, respectively.

ActionScript 3.0: You use the same process for ActionScript 3.0 but the properties are scrollV and maxScrollV.

txtFld.scrollV = txtFld.maxScrollV;

Horizontal scrolling is also possible, using scrollH and maxScrollH, respectively. See 15.7 Scrolling a Text Field for more information about scrolling a text field, as well as Chapter 18 for a comparison of text scrolling in ActionScript 2.0 and 3.0.

Triggering an ActionScript function with a hyperlink

ActionScript 2.0: Use the asfunction protocol to trigger a function. You can pass an argument to the function by following the function name with the argument value.

function doIt(msg:String):Void {
    trace(msg);
}

txtFld.htmlText = "<a href='asfunction:doIt,Hello'>link</a>";

ActionScript 3.0: Use the event protocol to trigger an event listener. You can pass a value to the function by querying the text properties.

txtFld.htmlText = "<a href='event:doIt'>link</a>";

txtFld.addEventListener(TextEvent.LINK, linkHandler);
function linkHandler(evt:TextEvent):void {
    if (evt.text == "doIt") {
        trace("doIt");
    }
}

See 15.13 Triggering ActionScript from HTML Links for more information about triggering ActionScript functions from text hyperlinks.

Sound

For all code snippets in this category, the following variables are used.

var snd:Sound = new Sound();
var sndChannel:SoundChannel = new SoundChannel();
var sndTransform:SoundTransform = new SoundTransform();

The Sound class is available to both ActionScript 2.0 and 3.0, while SoundChannel and SoundTransform are available to ActionScript 3.0 only. The SoundChannel class lets you play sounds in discrete channels for more granular control. The SoundTransform class contains transformation controls like pan and volume. You use a fourth class, SoundMixer, in ActionScript 3.0 to control all sounds in all channels, but it’s a static class and doesn’t need instantiating.

Loading and playing an external sound

ActionScript 2.0: Use the loadSound() method of the Sound class, and pass the sound path name to the method as a string. Play the sound using the start() method of the Sound class.

var snd:Sound = new Sound();
snd.loadSound("sound.mp3");
snd.onLoad = function():Void {
    snd.start();
};

ActionScript 3.0: Use the load() method of the Sound class and use the sound path name in a URLRequest instance. Play the sound using the play() method of the Sound class, assigning the sound to a channel.

snd.load(new URLRequest("sound.mp3"));
snd.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
function onComplete(evt:Event):void {
    channel = snd.play();
    snd.removeEventListener(Event.COMPLETE, onComplete);
}

See 17.6 Loading and Playing a Sound for more information about loading and playing sounds.

Playing an internal sound from the library

ActionScript 2.0: Use the attachSound() method of the Sound class, passing the library linkage name to the method. Play the sound using the start() method of the Sound class.

snd.attachSound("beep");
snd.start();

ActionScript 3.0: Use the sound’s class name to create an instance of the sound, and play it into a channel using the play() method.

var beepSound:Sound = new Beep();
sndChannel = beepSound.play();

Stopping a sound

ActionScript 2.0: Use the stop() method of the Sound class.

snd.stop();

ActionScript 3.0: Use the stop() method of the SoundChannel class.

sndChannel.stop();

Getting or setting a sound’s volume or pan

ActionScript 2.0: Use the getVolume() and setVolume() methods of the Sound class.

snd.setVolume(snd.getVolume()*.5);
snd.setPan(snd.getPan()*−1);

ActionScript 3.0: Modify the SoundTransform instance of the sound using the volume and pan properties, and reapply the transformation. See the next entry for more information.

sndTransform = sndChannel.soundTransform;
sndTransform.volume *= .5;
sndTransform.pan *= −1;
sndChannel.soundTransform = sndTransform;

Further, the complexity of ActionScript 2.0’s simultaneous volume and pan transformation approach is no longer needed.

ActionScript 2.0: Use the getTransform() method to store the current sound transformation of a sound in an object. Set the sound transformation properties. (The ll and lr values dictate what percentage of the left channel sound plays in the left and right channels, respectively. The rl and rr values dictate what percentage of the right channel sound plays in the left and right channels, respectively.) Reapply the transformation to the sound.

var sndTrans:Object = snd.getTransform();
sndTrans.ll = 0;
sndTrans.lr = 0;
sndTrans.rl = 100;
sndTrans.rr = 100;
snd.setTransform(sndTrans);

ActionScript 3.0: The general idea behind the sound transformation process is the same as with ActionScript 2.0 but less cryptic. You need only adjust the volume and pan properties of the SoundTransform instance rather than building the confusing object required in ActionScript 2.0. Note that percentage values are between 0 and 1, not 0 and 100. To transform a single sound, use the SoundChannel instance.

See the “Getting or setting a sound’s volume and pan” entry to modify a single sound or, to transform all sounds, use the SoundMixer class.

sndTransform = SoundMixer.soundTransform;
sndTransform.volume = 1;
sndTransform.pan = 1;
SoundMixer.soundTransform = sndTransform;

See 17.7 Setting the Volume and Pan of a Sound, as well as Chapter 18 for more information about setting the volume and pan of a sound.

Getting a sound’s duration

ActionScript 2.0: Use the duration property of the Sound class.

trace(snd.duration);

ActionScript 3.0: Use the length property of the Sound class.

trace(snd.length);

Getting a sound’s current time

ActionScript 2.0: Use the position property of the Sound class.

trace(snd.position);

ActionScript 3.0: Use the position property of the SoundChannel class.

trace(sndChannel.position);

Getting a loaded sound’s bytes loaded or total bytes

ActionScript 2.0: After using the loadSound() method, use the getBytesLoaded() and/or getBytesTotal() methods of the Sound class.

trace(snd.getBytesLoaded() + " of " + snd.getBytesTotal() + " bytes loaded");

ActionScript 3.0: Use the bytesLoaded and/or bytesTotal properties of the Sound class.

trace(snd.bytesLoaded + " of " + snd.bytesTotal + " bytes loaded");

Stopping all sounds

ActionScript 2.0: Use the global stopAllSounds() method.

stopAllSounds();

ActionScript 3.0: Use the stopAll() method of the SoundMixer class.

SoundMixer.stopAll();

Setting the buffer time of loaded sounds

ActionScript 2.0: Set the global _soundbuftime property to the number of seconds you wish to buffer.

_soundbuftime = 3;

ActionScript 3.0: Set the bufferTime property of the SoundMixer class to the number of seconds you wish to buffer.

SoundMixer.bufferTime = 3;

Network

Much of the IO (input/output) processes in ActionScript have changed with version 3.0. URLs are handled consistently, loading content classes are more specialized, and unloading assets requires quite a bit more attention. For additional information not covered here, see Chapter 17.

Using FlashVars

ActionScript 2.0: FlashVars are stored in the main timeline of a SWF file and, if you don’t find them, then you can use default values instead.

if (!imgURL) {
    var imgURL:String = "bg.jpg";
}

ActionScript 3.0: FlashVars are stored in the parameters object of the LoaderInfo class, and can be accessed through the loaderInfo property of the root.

var imgURL:String = "bg.jpg";
if (root.loaderInfo.parameters.imgURL) {
    imgURL = root.loaderInfo.parameters.imgURL;
}

See Chapter 18 for another example of using FlashVars.

Getting the URL of a SWF file

ActionScript 2.0: Use the global _url property from the _root.

trace(_root._url);

ActionScript 3.0: Use the url property of the root loaderInfo instance.

trace(root.loaderInfo.url);

You can see another example of accessing a URL, this time of loaded content, in the next section.

Loading and unloading an image or SWF file using loadMovie

ActionScript 2.0: Use the loadMovie() method of the MovieClip class.

var bg:MovieClip = this.createEmptyMovieClip("bgImg", 1);
bg.loadMovie("image.jpg");

To unload the image or SWF file, use the unloadMovie() method of the MovieClip class.

bg.unloadMovie();

ActionScript 3.0: Use the load() method of the Loader() class, a display object that can load images or SWF files. To unload the image or SWF file, use the unload() method of the instance.

var bg:Loader = new Loader();
addChild(bg);
bg.load(new URLRequest("image.jpg"));

bg.contentLoaderInfo.addEventListener(Event.INIT, onImageLoaded, false, 0, true);
function onImageLoaded(evt:Event):void {
    trace("bg URL:", bg.contentLoaderInfo.url);
    bg.unload();
}

See 17.2 Loading and Displaying an Image or SWF File and 17.5 Unloading an Image or SWF File for more information about loading and unloading external SWF files or images.

Loading and unloading an image or SWF file using MovieClipLoader

ActionScript 2.0: You can also use the MovieClipLoader class to load images or SWF files, in conjunction with a listener.

var bg:MovieClip = this.createEmptyMovieClip("img", 1);

var mclListener:Object = new Object();
mclListener.onLoadInit = function(mc:MovieClip) {
    trace(mc._url);
}

var bg_mcl:MovieClipLoader = new MovieClipLoader();
bg_mcl.addListener(mclListener);
bg_mcl.loadClip("image.jpg", bg);

ActionScript 3.0: MovieClipLoader has been removed. Use the Loader class instead. See the “Loading and unloading an image or SWF file using loadMovie” entry for a sample use of the Loader class.

Loading variables using LoadVars

For both ActionScript 2.0 and 3.0 versions of this example, a text file called userdata.txt contains the following URL-encoded variables.

user1=Sally&age1=2&user2=Claire&age2=0

ActionScript 2.0: Use the load() method of the LoadVars class to load the variables. After loading, use the decode() method to convert the loaded string to object properties.

var ldVar:LoadVars = new LoadVars();
ldVar.onLoad = function(success:Boolean) {
    if (success) {
        trace(this);
        ldVar.decode();
        trace(ldVar.user1);
    } else {
        trace("Error loading variables.");
    }
};
ldVar.load("userdata.txt");

ActionScript 3.0: Use the load() method of the URLLoader class to load the variables. Due to the dataFormat property of URLLoaderDataFormat.VARIABLES, the loaded data can already be queried by variable name.

var req:URLRequest = new URLRequest("userdata.txt");
var vars:URLLoader = new URLLoader();
vars.dataFormat = URLLoaderDataFormat.VARIABLES;
vars.addEventListener(Event.COMPLETE, onVarsLoaded);
try {
    vars.load(req);
} catch (err:Error) {
    trace("Variable load error:", err.message);
}

function onVarsLoaded(evt:Event):void {
    var ldr:URLLoader = URLLoader(evt.target);
    trace(ldr.data);
    trace(ldr.data.user1);
}

Sending variables using LoadVars

ActionScript 2.0: To send data to a server, define both send and receive instances of LoadVars, create variable properties and values in the send instance, and use the sendAndLoad() method of the class. The following example assumes that a server-based script returns a name-value pair with a variable called confirm.

var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function(success:Boolean) {
    if (success) {
        trace(result_lv.confirm);
    } else {
        trace("LoadVars error.");
    }
};
var login_lv:LoadVars = new LoadVars();
login_lv.user = "pfj";
login_lv.pass = "isn";
login_lv.sendAndLoad("http://<yourdomain>/login.php", result_lv, "POST");

ActionScript 3.0: To send variables to a server in ActionScript 3.0, first create the variables as properties of a URLVariables instance. Then assign the instance to the data property of a URLRequest instance that links to your server script. To receive data returned by the server, use the load() method, as seen in the previous ActionScript 3.0 example in this entry. If you don’t need a response, use the sendToURL() method, as seen here.

var vars:URLVariables = new URLVariables();
vars.name = "Graham Lewis";

var req:URLRequest = new URLRequest("http://<yourdomain>/login.php");
req.data = vars;

try {
    sendToURL(req);
} catch (err:Error) {
    trace("Error sending vars:", err.message);
}

Connecting to a URL in a web browser

ActionScript 2.0: Use the global getURL() method.

getURL("http://www.google.com", "_blank");

ActionScript 3.0: Use the global navigateToURL() method with a URLRequest instance.

navigateToURL(new URLRequest("http://www.google.com"), "_blank");

See Chapter 18 for additional examples of opening a URL.

Miscellaneous

Entirely written from scratch, changes permeate every nook and cranny of ActionScript 3.0, and some don’t necessarily warrant their own category.

Examining property underscores and name changes

ActionScript 2.0: Many, but not all, properties are preceded by an underscore:

toolTip._x = this._xmouse;

ActionScript 3.0: Property names don’t begin with an underscore and, on occasion, have been renamed to be more consistent with ActionScript 3.0 naming conventions, including the use of camel case.

toolTip.x = this.mouseX;

See Chapter 18 for additional examples of property underscores.

Using event and constant names

ActionScript 2.0: Event and constant names (as well as properties serving the role of a constant), don’t share any particular naming or usage conventions. Seen here, the value for the autoSize property is a string.

var txtFld:TextField = this.createNewTextField("txt", 1, 0, 0, 100, 100);
txtFld.autoSize = "left";

ActionScript 3.0: Corresponding structures are stored in classes for consistent use and reliable recall. The value for the autoSize property in this syntax is a constant.

var txtFld:TextField = new TextField();
txtFld.autoSize = TextFieldAutoSize.LEFT;

See 15.6 Automatically Sizing a Text Field for information about automatically sizing a text field, including the use of the corresponding constant.

Using Intervals and Timeouts

ActionScript 2.0: Repeating timed executions of functions are achieved with the setInterval() method and halted with the clearInterval() method, as seen in the following code. Note that you must manually halt the process if you want a finite number of executions.

//setInterval
var i:Number = 0;
var intID:Number = setInterval(showMsg, 1000);
function showMsg():Void {
    trace("interval");
    i++;
    if (i == 5) { clearInterval(intID); }
}

A single, delayed execution of a function is achieved with the setTimeout() method, and halted by the clearTimeout() method, as you see in the following new example.

//setTimeout
var timeoutID:Number = setTimeout(showMsg, 1000);
function showMsg():Void {
    trace("timeout");
    clearTimeout(timeoutID);
}

ActionScript 3.0: The Timer class makes intervals and timeouts easy. An ongoing timer functions much the same way as an interval, but with the consistency of event listeners. (Note that the timer must be started.) All timers must be stopped, and their event listeners removed when no longer needed, or the file containing the timer cannot be unloaded.

//ongoing interval
var i:int = 0;
var timr:Timer = new Timer(1000);
timr.addEventListener(TimerEvent.TIMER, onTimer, false, 0, true);
function onTimer(evt:TimerEvent):void {
    trace("interval behavior");
    i++
    if (i == 5) {
        timr.stop();
        timr.removeEventListener(TimerEvent.TIMER, onTimer);
    }
}
timr.start();

A single execution (as in when setTimeout() is desired), or even a finite number of executions not limited to 1, is even easier to use. An optional second parameter of the Timer class lets you specify how many times the timer fires and automatically stops the timer after the last execution.

//single execution
var i:int = 0;
var timr2:Timer = new Timer(1000, 1);
timr2.addEventListener(TimerEvent.TIMER, onTimer, false, 0, true);
function onTimer(evt:TimerEvent):void {
    trace("timeout behavior");
    timr2.removeEventListener(TimerEvent.TIMER, onTimer);
}
timr2.start();

See 14.11 Using a Timer to Dispatch Events for more information about using Timers.

Getting and setting the year of a date instance

ActionScript 2.0: The getYear() method of the Date class returns a year integer since 1900. (The year 2008 yields 108, for example.) Similarly, the setYear() method lets you set the year of a date object.

var today:Date = new Date();
today.setYear(today.getYear() + 1);

ActionScript 3.0: This method was removed because it was not ECMA-compliant. Use the getFullYear() and setFullYear() methods instead, which use full years, such as 2008. (Consider switching to these methods exclusively in any ongoing ActionScript 2.0 projects, as well, to make future migration to ActionScript 3.0 easier.)

var today:Date = new Date();
today.setFullYear(today.getFullYear() + 1);

Accessing private namespaces

ActionScript 2.0: Subclasses can access private properties or methods of a super class.

ActionScript 3.0: The private namespace now restricts access to a class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.236.191