BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?

Actionscript Cookbook
Actionscript Cookbook Solutions and Examples for Flash MX Developers

By Joey Lott

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: ActionScript Basics
Using ActionScript, you can create Flash movies that do just about anything you can imagine. But before launching into the vast possibilities, let's start with the basic foundation. The good news is that ActionScript commands follow a well-defined pattern, sharing similar syntax, structure, and concepts. Mastering the fundamental grammar puts you well on the way to mastering ActionScript.
This chapter addresses the frequent tasks and problems that relate to core ActionScript knowledge. Whether you are a beginner or master—or somewhere in between—these recipes help you handle situations that arise in every ActionScript project.
This book assumes you are familiar with the Flash authoring tool and have entered some basic ActionScript in the past, perhaps using the built-in Actions. ActionScript code is entered in the Actions panel (Window Actions), as shown in Figure 1-1.
Figure 1-1: The Actions panel in Expert Mode
We'll be entering our code in Expert Mode, which allows us to type the desired code into the Actions panel's script pane, also shown in Figure 1-1. Activate Expert Mode using the pop-up Options menu in the Actions panel, as shown in Figure 1-2. The menu in Figure 1-2 also displays useful configuration options, such as whether to display line numbers or auto-format your ActionScript code.
Figure 1-2: Activating Expert Mode
ActionScript's trace( ) command is used to display text in the Output window during authoring, as seen in Figure 1-3. To enter a script, you'll highlight a frame in the timeline and then open the Actions panel (the easiest way to open the Actions panel is using the shortcut key, F9). Code can also be attached directly to a movie clip or button, but attaching code to the timeline is usually preferred. Many developers add a scripts layer to their timeline, and that is where they attach their code.
Figure 1-3: The Flash authoring tool's Output window
The Output window is useful for debugging and is displayed automatically whenever trace( ) actions are executed (but only in the Test Player.) Recipe 8.9 and Recipe 11.15 display text at runtime to provide user feedback or assist in debugging.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Using ActionScript, you can create Flash movies that do just about anything you can imagine. But before launching into the vast possibilities, let's start with the basic foundation. The good news is that ActionScript commands follow a well-defined pattern, sharing similar syntax, structure, and concepts. Mastering the fundamental grammar puts you well on the way to mastering ActionScript.
This chapter addresses the frequent tasks and problems that relate to core ActionScript knowledge. Whether you are a beginner or master—or somewhere in between—these recipes help you handle situations that arise in every ActionScript project.
This book assumes you are familiar with the Flash authoring tool and have entered some basic ActionScript in the past, perhaps using the built-in Actions. ActionScript code is entered in the Actions panel (Window Actions), as shown in Figure 1-1.
Figure 1-1: The Actions panel in Expert Mode
We'll be entering our code in Expert Mode, which allows us to type the desired code into the Actions panel's script pane, also shown in Figure 1-1. Activate Expert Mode using the pop-up Options menu in the Actions panel, as shown in Figure 1-2. The menu in Figure 1-2 also displays useful configuration options, such as whether to display line numbers or auto-format your ActionScript code.
Figure 1-2: Activating Expert Mode
ActionScript's trace( ) command is used to display text in the Output window during authoring, as seen in Figure 1-3. To enter a script, you'll highlight a frame in the timeline and then open the Actions panel (the easiest way to open the Actions panel is using the shortcut key, F9). Code can also be attached directly to a movie clip or button, but attaching code to the timeline is usually preferred. Many developers add a scripts layer to their timeline, and that is where they attach their code.
Figure 1-3: The Flash authoring tool's Output window
The Output window is useful for debugging and is displayed automatically whenever trace( ) actions are executed (but only in the Test Player.) Recipe 8.9 and Recipe 11.15 display text at runtime to provide user feedback or assist in debugging.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Mathematical Operators
You want to modify something over time, such as the rotation or position of a movie clip.
Use the compound assignment operators to change a variable or property in increments. Or, if incrementing or decrementing by one, use the prefix or postfix increment or decrement operators.
Often, you'll want the new value of a variable or property to depend on the previous value. For example, you might want to move a movie clip to a new position that is 10 pixels to the right of its current position.
In an assignment statement—any statement using the assignment operator (an equals sign)—the expression to the right of the equals sign is evaluated and the result is stored in the variable or property on the left side. Therefore, you can modify the value of a variable in an expression on the right side of the equation and assign that new value to the very same variable on the left side of the equation.
Although the following may look strange to those who remember basic algebra, it is very common for a variable to be set equal to itself plus a number:
// Add 6 to the current value of myNum and assign that new value back to myNum. For
// example, if myNum was 3, this statement sets it to 9.
myNum = myNum + 6;
However, when performing mathematical operations, it is often more convenient to use one of the compound assignment operators, which combine a mathematical operator with the assignment operator. The +=, -=, *=, and /= operators are the most prevalent compound assignment operators. When you use one of these compound assignment operators, the value on the right side of the assignment operator is added to, subtracted from, multiplied by, or divided into the value of the variable on the left, and the new value is assigned to the same variable. The following are a few examples of equivalent statements.
These statements both add 6 to the existing value of myNum:
myNum = myNum + 6;
myNum += 6;
These statements both subtract 6 from the existing value of myNum:
myNum = myNum - 6;
myNum -= 6;
These statements both multiply
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Checking Equality or Comparing Values
You want to check if two values are equal.
Use the equality (or inequality) or strict equality (or strict inequality) operator to compare two values. To check whether a value is a valid number, use isNaN( ).
Equality expressions always return a Boolean value indicating whether the two values are equal. The equality (and inequality) operators come in both regular and strict flavors. The regular equality and inequality operators check whether the two expressions being compared can be resolved to the same value after converting them to the same datatype. For example, note that the string "6" and the number 6 are considered equal because the string "6" is converted to the number 6 before comparison:
trace(5 == 6);    // Displays: false
trace(6 == 6);    // Displays: true
trace(6 == "6");  // Displays: true
trace(5 == "6");  // Displays: false
The logical inequality operator (!=) returns false if two values are equal and true if they are not equal. If necessary, the operands are converted to the same datatype before the comparison:
trace(5 != 6);    // Displays: true
trace(6 != 6);    // Displays: false
trace(6 != "6");  // Displays: false
trace(5 != "6");  // Displays: true
On the other hand, the strict equality and inequality operators first check whether the values being compared are of the same datatype before performing the comparison. Differences in datatype cause the strict equality operator to return false and the strict inequality operator to return true:
trace(6 === 6);    // Displays: true
trace(6 === "6");  // Displays: false
trace(6 !== 6);    // Displays: false
trace(6 !== "6");  // Displays: true
There is a big difference between the assignment operator (=) and the equality operator (==). If you use the assignment operator instead of the equality operator, you change the variable's value rather than testing its current value.
Using the wrong operator leads to unexpected results. In the following example, myVar equals 5 at first, so you might expect the subsequent if statement to always evaluate to false, preventing the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Performing Actions Conditionally
You want to perform an action only when a condition is true.
Use an if statement or a switch statement.
You often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute an action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :).
The conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situation. The if statement is most appropriate when you want to tell your Flash movie to do something only when a certain condition is met (i.e., when the condition is true). When you have several possible conditions to test, you can use the switch statement instead. And you can use Flash's ternary conditional operator to perform conditional checking and assignment on a single line.
First, we'll look at the if statement. Of the conditional statements in ActionScript, the if statement is the most important to understand. In its most basic form, an if statement includes the keyword if followed by the test expression whose truthfulness you want to evaluate to determine which action or actions to execute. The test expression must be in parentheses, and the statement(s) to be executed should be within curly braces (the latter is mandatory if there is more than one statement in the statement block).
Here, we check whether animalName contains the word "turtle". This might be used to check whether the user answered a quiz question correctly (here, animalName is a variable assumed to contain the user's answer). Note that the double equals sign (==) is used to test whether two items are equal. It should not be confused with the single equals sign (=), which is used to assign a value to an item.
if (animalName == "turtle") {
  // This trace(  ) statement executes only when animalName is equal to "turtle".
  trace("Yay! 'Turtle' is the correct answer.");
}
Additionally, you can add an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Performing Complex Conditional Testing
You want to make a decision based on multiple conditions.
Use the logical AND (&&), OR (||), and NOT (!) operators to create compound conditional statements.
Many statements in ActionScript can involve conditional expressions, including if, while, and for statements, and statements using the ternary conditional operator. To test whether two conditions are both true, use the logical AND operator (&&), as follows (see Chapter 10 for details on working with dates):
// Check if today is April 17th.
now = new Date(  );
if (now.getDate() == 17 && now.getMonth(  ) == 3) {
  trace ("Happy Birthday, Bruce!");
}
You can add extra parentheses to make the logic more apparent:
// Check if today is April 17th.
if ((now.getDate() == 17) && (now.getMonth(  ) == 3)) {
  trace ("Happy Birthday, Bruce!");
}
Here we use the logical OR operator (||) to test whether either condition is true:
// Check if it is a weekend.
if ((now.getDay() == 0) || (now.getDay(  ) == 6) ) {
  trace ("Why are you working on a weekend?");
}
You can also use a logical NOT operator (!) to check if a condition is not true:
// Check to see if the name is not Bruce.
if (!(name == "Bruce")) {
  trace ("This application knows only Bruce's birthday.");
}
The preceding example could be rewritten using the inequality operator (!=):
if (name != "Bruce") {
  trace ("This application knows only Bruce's birthday.");
}
Any Boolean value, or an expression that converts to a Boolean, can be used as the test condition:
// Check to see if a movie clip is visible. If so, display a message. This condition
// is shorthand for myMovieClip._visible == true.
if (myMovieClip._visible) {
  trace("The movie clip is visible.");
}
The logical NOT operator is often used to check if something is false, rather than true:
// Check to see if a movie clip is invisible (not visible). If so, display a message.
// This condition is shorthand for myMovieClip._visible != true or 
// myMovieClip._visible == false
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Repeating an Operation Many Times
You want to perform a task multiple times within a single frame.
Use a loop to perform the same task multiple times within a single frame. For example, you can use a for statement:
for (var i = 0; i < 10; i++) {
  // Display the value of i.
  trace(i);
}
When you want to execute the same action (or slight variations thereof) multiple times within a single frame, use a looping statement to make your code more succinct, easier to read, and easier to update. You can use a while statement or a for statement for this purpose, but generally a for statement is the better choice. Both statements achieve the same result, but the for statement is more compact and more familiar to most programmers.
The syntax of a for statement consists of five basic parts:
The for keyword
Every for statement must begin with a for keyword.
Initialization expression
The loop typically employs an index variable (a.k.a. a loop counter) that is initialized when the statement is first encountered. The initialization is performed only once regardless of how many times the loop is repeated.
Test expression
A loop should include a test expression that returns true or false. The test expression is evaluated once each time through the loop. Generally, the test expression compares the index variable to another value, such as a maximum number of loop iterations. The overall expression must evaluate to true for the for statement's body to execute (contrast this with a do . . . while loop, which executes at least once, even if the test expression is false). On the other hand, if the test expression never becomes false, you'll create an infinite loop, resulting in a warning that the Flash Player is running slowly (which appears after 15 seconds).
Update expression
The update expression usually updates the value of the variable used in the test expression so that, at some point, the test expression becomes false and the loop ends. The update expression is executed once each time through the loop. An infinite loop is often caused by failing to update the appropriate variable in the update expression (usually the same variable used in the test expression).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Performing an Action Once per Frame Update
You want to perform an action or actions at the frame rate of the movie.
Use an onEnterFrame( ) handler.
The onEnterFrame( ) event handler method for movie clips is the appropriate choice when you want to perform actions continuously at the same speed as the frame rate of the movie. See Recipe 1.1 and Recipe 7.8.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Repeating a Task at Timed Intervals
You want to perform an action or actions at a specific timed interval.
Use the setInterval( ) function.
The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie.
// Define a function.
function myIntervalFunction (  ) {

  // Output the difference between the current timer value and its value from the
  // last time the function was called.
  trace(getTimer(  ) - lastTime);
  lastTime = getTimer(  );
}

// Set up an interval that attempts to invoke myIntervalFunction(  ) once every
// millisecond.
setInterval(myIntervalFunction, 1);
In the preceding example, even though the interval is theoretically one millisecond, in practice, its accuracy and granularity depend on computer playback performance in relation to other tasks being demanded of the processor. There are two implications to this:
  • Don't rely on intervals to be extremely precise.
  • Don't rely on intervals to be smaller than a few milliseconds.
The setInterval( ) function returns an identifier for the newly created interval. If you want to be able to stop the interval at a later time, you must store the return value, as follows:
// Set an interval such that someFunction(  ) is called approximately once per second.
// Assign setInterval(  )'s return value to the variable myIntervalID for later use.
myIntervalID = setInterval(someFunction, 1000);
You can use the clearInterval( ) function to stop an interval if you know the interval's identifier:
clearInterval(myIntervalID);
If you want the interval to invoke the method of an object instead of a standalone function, you can use the variation of the setInterval( ) function in which you pass it three parameters—a reference to the object, the name of the function (as a string), and the interval in milliseconds— instead of just two:
// Create a simple object using the Object constructor.
obj = new Object(  );

// Assign a method named myMethod
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Reusable Code
You want to perform a series of actions at various times without duplicating code unnecessarily throughout your movie.
Create a function and then call (i.e., invoke) it by name whenever you need to execute those actions.
There is more than one way to create (i.e., define or declare) a function. Here is how to create a named function:
function functionName (  ) {
  // Statements go here.
}
To call (i.e., execute) the named function, refer to it by name, such as:
                  functionName(  );
Here is how to create a function literal:
                  functionName = function (  ) {
  // Statements go here.
};
Although not strictly required, it is considered a best practice to include a semicolon following the closing curly brace when defining a function literal.
Grouping statements into a function allows you to define the function once but execute it as many times as you'd like. This is useful when you need to perform similar actions at various times without duplicating the same code in multiple places. Keeping your code centralized in functions makes it easier to understand (because you can write the function once and then ignore the details when using it) and easier to maintain (because you can make changes in one place rather than in multiple places).
There are two common ways of defining ActionScript functions: as named functions or function literals (a.k.a. anonymous functions). Each of these ways of declaring a function has its own use.
The named function declaration is the most common choice (when not defining a function to be used as a method) and has at least one advantage over function literals: named functions are accessible within the entire keyframe (or on( ) or onClipEvent( ) handler) even if they come after the call to the function.
For example, even though the writeMessage( ) function is not declared until after it is invoked, the function is still available:
// Invoke the writeMessage(  ) function, which is declared later in the script.
writeMessage(  );

// Declare (define) the 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generalizing a Function to Enhance Reusability
You want to perform slight variations of an action without having to duplicate multiple lines of code to accommodate the minor differences.
Add parameters to your function to make it flexible enough to perform slightly different actions when it is invoked rather than performing exactly the same action or producing the same result each time.
Define the parameters that account for the variability in what you want the function to do:
function myParamsFunction (param1, param2, param3) {
  trace("The average is " + (param1 + param2 + param3)/3);
}
If you don't know the exact number of parameters the function will receive, use the built-in arguments array to handle a variable number of parameters.
A function that doesn't accept parameters generally produces the same result each time it is invoked. But you often need to perform almost exactly the same actions as an existing function, but with minor variations. Duplicating the entire function and then making minor changes to the second version is a bad idea in most cases. Usually, it makes your code harder to maintain and understand. More importantly, you'll usually find that you need not only two variations but many variations of the function. It can be a nightmare to maintain five or six variations of what should ideally be wrapped into a single function. The trick is to create a single function that can accept different values to operate on.
For example, if you have an average( ) function, you want to specify arbitrary values to be averaged each time it is invoked, instead of having it always average the same two numbers. You can accomplish this goal using parameters.
The most common way to work with parameters is to list them within the parentheses in the function declaration. The parameter names should be separated by commas, and when you invoke the function you should pass it a comma-delimited list of arguments that correspond to the parameters it expects.
The terms "parameters" and "arguments" are often used interchangeably to refer to the variables defined in the function declaration or the values that are passed to a function when it is invoked.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exiting a Function
You want to exit a function.
Functions terminate automatically after the last statement within the function executes. Use a return statement to exit a function before reaching its end.
The return statement exits the current function, and the ActionScript interpreter continues the execution of the script that initially invoked the function. Any statements within the function body that follow a return statement are ignored.
function myFunction (  ) {
  return;
  trace("Never called");
}

myFunction(  );
// Execution continues here after returning from the myFuction(  ) invocation.
In the preceding example, the return statement causes the function to terminate before performing any actions, so it is not a very useful function. More commonly, you will use a return statement to exit a function under certain conditions. This example exits the function if the password is wrong:
function checkPassword (password) {

  // If password is not "SimonSays", exit the function.
  if (password != "SimonSays") {
    return;
  }

  // Otherwise, perform the rest of the actions.
  gotoAndStop ("TreasureMap");
}

// This function call uses the wrong password, and so the function exits.
checkPassword("MotherMayI");

// This function uses the correct password, and so the function jumps to the 
// TreasureMap frame.
checkPassword("SimonSays");
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Obtaining the Result of a Function
You want to perform a function and return the results to the script that invoked the function.
Use a return statement that specifies the value to return.
The return statement, when used without any parameters, simply terminates a function. Technically, return returns the value undefined to the caller if no value is specified. Likewise, if there is no return statement, the function returns undefined when it terminates. But any value specified after the return keyword is returned to script that invoked the function. Usually, the returned value is stored in a variable for later use:
function average (a, b) {
  // Return the average of a and b.
  return (a + b)/2;
}

var playerScore ;
// Call the average(  ) function and store the result in a variable.
playerScore = average(6, 12);
// Use the result in some way.
trace("The player's average score is " + playerScore);
You can use the return value of a function, without storing it in a variable, by passing it as a parameter to another function:
trace("The player's average score is " + average(6, 12));
Note, however, that if you do nothing with the return value of the function, the result is effectively lost. For example, this statement has no detectable benefit because the result is never displayed or used in any way:
average(6, 12);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Avoiding Conflicting Variables
You want to make sure that variables within a function do not interfere with variables in other functions or within the timeline in which the function is defined.
Use the var keyword to declare local variables.
Generally, you should declare variables used within functions as local variables. Local variables are known only within the function. Therefore, they do not conflict with variables of the same name in other functions or within the timelines in which the functions are defined. To make a variable local, declare it with the var keyword. Parameters are automatically treated as local variables, so you do not need to include the var keyword when declaring parameters for a function.
function localVarsFunction (param1, param2) {
  var myVar;
  myVar = "Local variables are fun.";
}
Or, more succinctly, you can write:
function localVarsFunction (param1, param2) {
  var myVar = "Local variables are fun.";
}
Variables declared without the var keyword are implicitly scoped to the timeline on which they reside (note that unlike some languages, ActionScript doesn't require you to declare a variable before assigning it a value for the first time). In this case, myVar is a timeline variable, not a local variable, even though it is declared within a function:
function timelineVarsFunction (  ) {
  myVar = "Timeline variables are fun but not usually a good choice in functions.";
}
To declare a global variable, attach it as a property to the _global object, as follows:
_global.companyName = "Person13";
Once declared, a global variable can be accessed from anywhere in the movie by simply using its name, as follows:
trace ("Welcome to the " + companyName + "web site.");
However, a local variable of the same name will override the global variable:
function localVarsFunction (  ) {
  var companyName = "Macromedia";
  // This displays "Welcome to the Macromedia web site."
  trace ("Welcome to the " + companyName + "web site.");

  // To access the global variable of the same name, precede it with _global.
  // This displays "Welcome to the Person 13 web site."
  trace ("Welcome to the " + _global.companyName + "web site.");
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reusing and Organizing Code in Multiple Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor.
Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies:
// Adds all the code within MyActionScriptFile.as to your Flash movie.
#include "MyActionScriptFile.as"
Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file to a .swf file. When you export a .swf file, Flash replaces the #include directive with the contents of the specified file. The external file must be a text file with valid ActionScript code in it. By convention the file should be named with the .as extension, though it is not absolutely necessary:
#include "ASutils.as"
Notice that the #include directive is not followed by a semicolon. Adding a semicolon causes an error.
Additionally, Flash must be able to locate the file when you export the movie. Therefore, you should place the file in a location relative to where the Flash document is saved. For example, the previous example looks for a file named ASutils.as in the same directory as the .fla document. You can also place the file in a subdirectory of the directory in which the Flash document is saved:
// Look for a file named ASutils.as in a subdirectory named myASFiles.
#include "myASFiles/ASutils.as"
You can also place the ActionScript files in the Flash installation's Include directory. And, in fact, this is recommended for all ActionScript files that you anticipate you might use in multiple movies. If Flash cannot find a file with the specified name relative to the .fla file, it looks in the Configuration\Include subdirectory of the directory in which Flash is installed. For example, on Windows-based computers, the default Include folder is located in C:\ProgramFiles\Macromedia\Flash MX\Configuration\Include.
If Flash is unable to find the external file in the folder specified by the #include directive (by default, the same directory as the .fla file) and is unable to find the file within the Flash
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Runtime Environment
Flash Player 6 offers a relatively large amount of information about and control over the runtime environment. ActionScript's System.capabilities object returns information about the Player and the computer on which it is running, such as the operating system, language, and audio capabilities. The System object also allows you to control some elements of the Player such as the right-click menu under Windows (Ctrl-click on the Macintosh) and the Settings dialog box. The Stage object controls the scaling and alignment of the movie within the Player.
You want to know the user's Flash Player version.
Use a plugin-detection script that runs in the browser before loading the Flash Player, or use ActionScript (System.capabilities.version, getVersion( ), or $version) within the Flash Player, as supported by the minimum Player version you expect to encounter.
There are two broad categories of Flash Player version detection: you can attempt to detect the Player version with a browser-based script before the Player loads, or you can use ActionScript within the Flash Player to check the version that is currently running.
The problem with the first method is that it doesn't work on all platforms and with all browsers, as explained in part at http://www.macromedia.com/support/flash/ts/documents/browser_support_matrix.htm.
Therefore, you should guard against a "false negative" in your detection approach; even if you fail to detect the Flash Player plugin, you should give the user the option of telling you that he has the plugin installed and would like to view your Flash content (i.e., don't force visitors to the Macromedia Flash installation page just because you can't detect their Player version).
There is a wealth of existing documentation on detecting the presence and version of the Flash Player plugin with a browser script, so refer to the following URLs for explanations and examples.
Macromedia Technote 14526, "How to detect the presence of the Flash Player," is a good starting point:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Flash Player 6 offers a relatively large amount of information about and control over the runtime environment. ActionScript's System.capabilities object returns information about the Player and the computer on which it is running, such as the operating system, language, and audio capabilities. The System object also allows you to control some elements of the Player such as the right-click menu under Windows (Ctrl-click on the Macintosh) and the Settings dialog box. The Stage object controls the scaling and alignment of the movie within the Player.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Detecting the Player Version
You want to know the user's Flash Player version.
Use a plugin-detection script that runs in the browser before loading the Flash Player, or use ActionScript (System.capabilities.version, getVersion( ), or $version) within the Flash Player, as supported by the minimum Player version you expect to encounter.
There are two broad categories of Flash Player version detection: you can attempt to detect the Player version with a browser-based script before the Player loads, or you can use ActionScript within the Flash Player to check the version that is currently running.
The problem with the first method is that it doesn't work on all platforms and with all browsers, as explained in part at http://www.macromedia.com/support/flash/ts/documents/browser_support_matrix.htm.
Therefore, you should guard against a "false negative" in your detection approach; even if you fail to detect the Flash Player plugin, you should give the user the option of telling you that he has the plugin installed and would like to view your Flash content (i.e., don't force visitors to the Macromedia Flash installation page just because you can't detect their Player version).
There is a wealth of existing documentation on detecting the presence and version of the Flash Player plugin with a browser script, so refer to the following URLs for explanations and examples.
Macromedia Technote 14526, "How to detect the presence of the Flash Player," is a good starting point:
http://www.macromedia.com/support/flash/ts/documents/uber_detection.htm
See also the Player-detection discussion in the Flash Deployment Kit:
http://www.macromedia.com/support/flash/player/flash_deployment_readme/
The standard third-party browser-based Flash plugin-detection tool is the Moock Flash Player Inspector:
http://www.moock.org/webdesign/flash/detection/moockfpi/
Testing the Flash Player version from ActionScript can be problematic because the user might not have the Player installed at all (in which case your movie and its ActionScript code are never executed), or the installed version may not support the latest ActionScript techniques. Therefore, it is typical to use the lowest common denominator for checking Flash Player versions (you can use the more modern techniques if you are sure the user will have at least a known minimum version). Naturally, if your movie is running in the Standalone Player, you can't use the browser-based plugin-detection scripts, but you can build the executable with whatever version of Flash you choose.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Detecting the Operating System
You want to know the operating system under which the Flash movie is being played, perhaps to indicate which operating systems are not supported or to implement a platform-specific feature.
Use the $version or System.capabilities.os property.
In Recipe 2.1, we saw that the $version property string includes the operating system on which the Player is running. The operating system can be either "MAC", "WIN", or "UNIX".
playerParts = _level0.$version.split(" ");
switch (playerParts[0]) {
  case "MAC":
    gotoAndStop ("WelcomeMac");
    break;
  case "WIN":
    gotoAndStop ("WelcomeWindows");
    break;
  case "UNIX":
    gotoAndStop ("WelcomeUnix");
}
As of Flash 6, you can use the System.capabilities.os property, which returns a string indicating the operating system and version name. Possible values include "Windows XP", "Windows 2000", "Windows NT", "Windows 98/Me", "Windows 95", and "Windows CE". On the Macintosh, the string includes the version number, such as "MacOS 9.2.1" or "MacOS 10.1.4".
You can make design choices based on the operating system. For example, your movie might load different assets depending on the user's operating system, or you may simply want to record the operating systems of the users who view your movies for statistical analysis.
If all you care about is the general platform type instead of the specific version, you can check just the first three letters of the string, as follows:
os = System.capabilities.os.substr(0, 3);
if (os == "Win") {
  // Windows-specific code goes here.
} else if (os == "Mac") {
  // Mac-specific code goes here.
} else {
  // Must be Unix or Linux
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Checking the System Language
You want to know what language is used on the computer playing the movie.
Use the System.capabilities.language property.
You can use the System.capabilities.language property to determine the language of the computer that is playing the movie. The property returns a two-letter ISO-639-1 language code (i.e., "fr" for French). Where applicable, a two-letter country code is appended, separated from the language code with a hyphen (i.e., "en-US" for U.S. English and "en-UK" for U.K. English).
For a summary of language codes, see the following resources:
http://lcweb.loc.gov/standards/iso639-2/englangn.html
http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
Here is an example of how to use the language property:
// Example output: en-US
trace(System.capabilities.language);
You can use this property to dynamically load content in the appropriate language:
// Create an associative array with language codes 
// for the keys and greetings for the values.
greetings = new Array(  );
greetings["en"] = "Hello";
greetings["es"] = "Hola";
greetings["fr"] = "Bonjour";

// Extract the first two characters from the language code.
lang = System.capabilities.language.substr(0, 2);

// Use a default language if the language is not in the list.
if (greetings[lang] == undefined) {
  lang = "en";
}

// Display the greeting in the appropriate language.
trace(greetings[lang]);
When you want to offer multiple language capabilities in your movies, you can choose from several different approaches. One approach, as shown in the preceding code, is to create associative arrays for all the text that appears in the movie. Another is to create static content in multiple movies (one for each language) and load those movies based on the language code. With this technique, each .swf filename should include the language code, such as myMovie_en.swf, myMovie_es.swf, myMovie_fr.swf, etc.
// Get the language from the capabilities
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Detecting Display Settings
You want to know the display settings for the device on which the movie is being played.
Use the screenResolutionX and screenResolutionY properties of the System.capabilities object.
You should use the System.capabilities object to determine the display settings of the device that is playing the movie. The screenResolutionX and screenResolutionY properties return the display resolution in pixels.
// Example output:
// 1024
// 768
trace(System.capabilities.screenResolutionX);
trace(System.capabilities.screenResolutionY);
You can use these values to determine how to display a movie or even which movie to load. These decisions are increasingly important as more handheld devices support the Flash Player. For example, the dimensions of a cell phone screen and a typical desktop computer display are different, so you should load different content based on the playback device:
resX = System.capabilities.screenResolutionX;
resY = System.capabilities.screenResolutionY;

// If the resolution is 240   ×   320 or less, then load the PocketPC movie version.
// Otherwise, assume the device is a desktop computer and load the regular content.
if ( (resX <= 240) && (resY <= 320) ) {
  _root.loadMovie("main_pocketPC.swf");
}
else {
  _root.loadMovie("main_desktop.swf");
}
You can also use the screen-resolution values to center a pop-up browser window:
resX = System.capabilities.screenResolutionX;
resY = System.capabilities.screenResolutionY;

// Set variables for the width and height of the new browser window.
winW = 200;
winH = 200;

// Determine the x and y values in order to center the window.
winX = (resX / 2) - (winW / 2);
winY = (resY / 2) - (winH / 2);

// Create the code that, when passed to getURL(  ), opens the new browser window.
jsCode = "javascript:void(newWin=window.open('http://www.person13.com/'," + 
         "'newWindow', 'width=" + winW +
         ", height=" +  winH + "," + 
         "left=" + winX + ",top=" + winY + "'));";

// Call the JavaScript function using 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scaling the Movie
You want to control how a movie fits in the Player, including the scaling.
Use the Stage.scaleMode property.
The Flash Player defaults to a scale mode of "showAll" (except the test Player, which defaults to "noScale"). In "showAll" mode, the Flash movie scales to fit the Player while maintaining the movie's original aspect ratio. The result is that the movie can have borders on the sides if the Player aspect ratio does not match the movie aspect ratio. You can set a movie to "showAll" mode, as follows:
Stage.scaleMode = "showAll";
The "noBorder" mode scales a movie to fit the Player while maintaining the original aspect ratio, but it forces the Player to display no borders around the Stage. If the aspect ratio of the Player does not match that of the movie, some of the movie will be cut off around the edges. You can set a movie to "noBorder" mode, as follows:
Stage.scaleMode = "noBorder";
The "exactFit" mode scales a movie to fit the Player and alters the movie's aspect ratio, if necessary, to match that of the Player. The result is that the movie always exactly fills the Player, but the elements of the movie may be distorted. For example:
Stage.scaleMode = "exactFit";
In "noScale" mode, the movie is not scaled, and it maintains its original size and aspect ratio regardless of the Stage's size. When you use the "noScale" mode, also set the movie's alignment (see Recipe 2.6). For example:
Stage.scaleMode = "noScale";
The scaleMode property's value does not prevent the user from being able to scale the movie using the right-click/Ctrl-click menu. However, you can disable those options in the menu, as shown in Recipe 2.9.
Additionally, you can affect scaling (among other things) in Standalone Projectors using a third-party utility such as SWF Studio (see Recipe 2.10).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing the Alignment
You want to change the alignment of the movie within the Player.
Use the Stage.align property.
Flash movies appear in the center of the Player by default. You can control the alignment of a movie within the Player by setting the Stage.align property, as shown in Table 2-1.
Table 2-1: Alignment as controlled by Stage.align
Value
Horizontal alignment
Vertical alignment
"T"
Center
Top
"B"
Center
Bottom
"L"
Left
Center
"R"
Right
Center
"C" or " "
Center
Center
"LT" or "TL"
Left
Top
"RT" or "TR"
Right
Top
"LB" or "BL"
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Detecting the Device's Audio Capabilities
You want to determine the audio capabilities of the device on which the Player is running.
Use the hasAudio and hasMP3 properties of the System.capabilities object.
Desktop versions of Flash Player 6 and later support MP3 playback and the ability to encode audio from a microphone or similar device. However, Flash Players for other devices do not necessarily support all, or possibly any, audio capabilities. The System.capabilities.hasAudio property returns true if the Player has any audio capabilities and false otherwise. This is extremely important for playing movies on multiple devices. If a device has no audio support, you should avoid forcing users to download something they cannot hear (especially because audio can be quite large):
// Load a .swf containing sound only if the Player can play audio.
if (System.capabilities.hasAudio) {
  mySoundHolder.loadMovie("sound.swf");
} else {
  mySoundHolder.loadMovie("silent.swf");
}
Just because a Player has audio capabilities, however, does not necessarily mean that it can play back MP3 sounds. Therefore, if publishing MP3 content, you should test for MP3 capabilities using the System.capabilities.hasMP3 property. MP3 sounds are preferable, if supported, because they offer better sound-quality-to-file-size ratios than ADCP sounds.
// If the Player can play MP3s, load an MP3 using a Sound object. Otherwise, load a 
// .swf containing ADCP sound into a nested movie clip.
if (System.capabilities.hasMP3) {
  mySound = new Sound(mySoundHolder);
  mySound.load("sound.mp3", false);
} else {
  mySoundHolder("adcpSound.swf");
}
It is important to understand that the hasAudio and hasMP3 property settings are based on the capabilities of the Player and not of the system on which the Player is running. The desktop system players (for Windows, Mac OS, and Linux) always return true for both properties regardless of whether the system actually has the hardware (i.e., soundcard and speakers) to play back sounds. However, players for other devices may return false if the device does not support the audio or MP3 features.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Prompting the User to Change Player Settings
You want to open the user's Flash Player Settings dialog box to prompt her to allow greater access to her local system.
Use the System.showSettings( ) method.
The System.showSettings( ) method opens the Flash Player Settings dialog box, which includes four tabs. The number in parentheses is the value you pass to showSettings( ) to open that particular tab.
Privacy (0)
Allows the user to specify whether to allow Flash access to her camera and microphone.
Local Storage (1)
Allows the user to specify how local shared objects are stored, including the maximum allowable disk usage.
Microphone (2)
Allows the user to select a microphone and adjust the volume.
Camera (3)
Allows the user to select a camera.
If you don't pass any parameters to the showSettings( ) method, it opens the Settings dialog box to the tab that was opened the last time the Settings dialog box was used. Here, we open the Settings dialog box to the Local Storage tab by explicitly specifying a value of 1:
// Open the Settings dialog box to the Local Storage tab.
System.showSettings(1);
Out of courtesy, you should prompt the user to open the Settings dialog box with a button rather than simply opening it without warning. Also, you should alert the user beforehand as to which settings to change.
Recipe 16.4
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hiding the Flash Player's Menu Items
You want to hide the right-click menu under Windows (Ctrl-click on the Macintosh).
You can't disable the Flash Player's pop-up menu entirely, but you can minimize the options shown in the menu by setting the Stage.showMenu property to false.
By default, the following options appear in the Flash Player's pop-up menu when the user right-clicks in Windows (or Ctrl-clicks on the Macintosh):
Zoom In
Zoom Out
100%
Show All
Quality (Low, Medium, or High)
Settings
Print
About Flash Player 6
You can remove most of the menu options with the following line of ActionScript code, although the Settings and About options remain in place:
Stage.showMenu = false;
Unfortunately, Flash does not provide a way to disable the menu entirely. Furthermore, Windows users are accustomed to using right-click to display a pop-up browser menu that allows them to open a link in a new window, for example. Such options are not available due to the Flash pop-up menu's presence. It is possible to use a third-party utility such as SWFKit or SWF Studio to completely disable the menu for enhanced Standalone Projectors (Windows versions only), as shown in Recipe 2.10.
See Recipe 2.8 for a way to display Flash's Settings dialog box without requiring the user to right-click (in Windows) or Ctrl-click (on Macintosh).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enhancing Standalone Projectors
You want to create an enhanced Standalone Projector with features such as borderless playback, custom titles, no Flash menus, and so on.
Use a third-party tool such as SWF Studio or SWFKit to create the Projector from your completed Flash movie.
SWF Studio is a third-party utility that helps you overcome some of the limitations of regular standalone Flash Projectors. However, SWF Studio produces Windows projectors only. Also note that the resultant projector files are rather hefty (minimum file size is around 1.5 MB). Therefore, projectors created with SWF Studio are more suited for distribution via CD-ROM or a kiosk than via download.
SWF Studio has many features, as described on the official product site (http://www.northcode.com). SWFKit (http://www.swfkit.com) offers similar feature enhancements, but we cover only SWF Studio in detail here.
However, regardless of the Projector enhancements you want to achieve, there are several steps necessary in any project that uses SWF Studio:
  1. Create your Flash movie by exporting the .swf file from Flash.
  2. Open SWF Studio. The program automatically starts with a new project opened, so you don't need to create a new project.
  3. On the left side of the application window is the Project Tree (see Figure 2-1). Locate the Layout option at the end of the list and click on it.
  4. In the right pane, click on the Layout Options button. A menu appears from which you should select Add Movie (see Figure 2-1).
  5. A new Movie is added to the project and appears as an item under the Layout option in the Project Tree. The Movie option should be selected automatically, and the right pane should now contain a File form field. Click on the Browse button to the right of the form field, select the .swf file you want to add to the project, and click OK.
  6. Select the enhancements you want to add to your projector (the default settings disable the right-click menu entirely).
  7. After you have chosen the settings for the Projector, click Build to export the EXE. If you saved the project previously, SWF Studio exports the EXE with that name; otherwise, it exports the EXE as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting the Dimensions of a Projector
Content preview·