Chapter 16: Creating Flash Applications with Components

Overview

The previous chapter introduced the fundamental ActionScript terms and some of the concepts of using the ActionScript language. In this chapter, you will peel back another layer and delve deeper into the world of Flash-based scripting.

So far, you have seen the possibilities that ActionScript can offer to your movies: It transforms them from simple linear animations to complex interactive applications and experiences. What is missing right now is a framework for you to use when constructing your scripts. You need to learn the conventions and rules of the language. Without these, it's impossible to use ActionScript to communicate intelligently.

 

Learning ActionScript Syntax

Like all spoken languages, computer languages such as ActionScript follow a particular set of rules, or syntax. It's crucial to understand the syntax of the language so that you can use it to say something meaningful. After all, the purpose of a language is to communicate, and ActionScript provides you with a communication link to Flash.

Knowing all of the ActionScript terms in this book can be helpful if you want to become an expert "ActionScripter." But it is even more important to know the rules that define how all the terms are used and how they work together as a language. Once you have grasped the rules of ActionScript syntax, you are well on your way to becoming a fluent "speaker" or scriptwriter, and an excellent communicator with your Flash movies.

Punctuation Marks in ActionScript

You will use several different punctuation marks when writing an ActionScript. You can use punctuation to issue a command or track the path to a movie or variable. It is also there to help annotate your scripts and provide both explanation and instruction. Mainly, the purpose of punctuation is to bring order to your scripts and organize their contents so that Flash can understand how the scripts should be executed.

ActionScript Dot Syntax

The ActionScript dot syntax was introduced when Flash evolved to version 5. The dot syntax makes ActionScript look similar to JavaScript. If you are comfortable with JavaScript, learning ActionScript will put you in familiar territory. The construction for the dot syntax is as follows :

The left side of the dot can refer to an object, instance, or Timeline in your movie. The right side of the dot can be a property, target path, variable, function, or even another object that is directed at or found within the element on the left side. Here are three examples:

 myClip._visible=0; 
 menuBar.menu1.item3=152; 
 _root.gotoAndPlay(5); 

In the first example, a Movie Clip named myClip is made invisible by setting the visible property to with the dot syntax. The second example shows the path to the variable item3 through menu1 , a nested Movie Clip in the Movie Clip named menuBar . The variable is assigned a value of 152. The third example uses the root reference to command the main Timeline to jump to frame 5 and play. In each example, you can see how the left side of the dot names or references an object, while the right side contains either a new object, or some kind of instruction or parameter that defines or manipulates the first object to the left of the dot.

 

Note  

The dot is also known as the dot operator because it can be used to issue commands and modify properties. For more information on other ActionScript operators, see the "Operators" section later in this chapter.

ActionScript Slash Syntax

The slash syntax was used in Flash 4 and has since been replaced by the dot syntax. Although slash syntax is still supported in Flash MX 2004 and MX Pro 2004, it is deprecated, or no longer preferred. This syntax was used primarily in Flash 4 to delimit target paths. For example, the path to the nested Movie Clip leg through the clips spider and body was expressed like this:

 "/spider/body/leg"; 

Now, using the dot syntax, the same path is written this way:

 spider.body.leg; 

The slash syntax was used to access variables belonging to other Timelines and was also used with the tellTarget function to target Movie Clips. Now that the tellTarget action has been deprecated, it's better to use the dot syntax and the with statement.

Comments

It is a good idea to make notes as you write your scripts. Notes can provide guidance or instructions to someone who has to edit your scripts. They can also be helpful if you are forced to abandon a project for a period of time; when you come back to the code, your notes will remind you what each part of the script was doing.

To make notes in ActionScript, you have to insert them as comments . To insert comments, type two forward slashes ( // ) and enter your notes after them. For example:

 // checks to see if all movie frames are loaded 
 if(_framesLoaded >=_totalFrames){ 
 // if TRUE, then it starts the move at frame 6 
   gotoAndPlay(6); 
 }else{ 
 // if FALSE, it loops back to frame 1 
   gotoAndPlay(1); 
 } 

In ActionScript, anything on the same line that follows the double slash will be ignored by Flash. This means that you can type anything you like after the slashes because Flash will not interpret comments as ActionScript. Comments also allow you to " turn off" parts of a script. If there are one or more lines that are causing problems, you can comment them out and run the script without those lines. Flash will ignore the commented lines and run everything else in the script. To learn more about this technique, see Chapter 21.

 

Tip  

To insert large notes or blocks of text within your scripts, you can use multiline comments ( /* ). This handy tool makes it easy to write long messages or explanations within the body of your ActionScripts. Simply begin the note with the opening character sequence ( /* ) and end with the closing sequence( */ ). All statements that are written between these markers will be ignored by the Flash Player.

When the ActionScript Editor Preferences are set to default, comments appear in the script window in a light gray color so that you can distinguish them from other parts of your script. To change this, select Flash Preferences (Mac) or Edit Preferences (Win) or choose Preferences from the Actions panel pop-up menu. Go to the ActionScript Editor tab and select a new color from the swatch menu next to the word Comments .

Curly Braces

ActionScript organizes the elements of a script by using the curly brace characters ( {} ). (These characters are also called curly brackets .) In the following script, all the statements between the pair of curly braces will be executed when the mouse is pressed:

 on(press){ 
   gotoAndStop(50); 
 } 

A script can also include multiple sets of curly braces:

 on(press){ 
   with(fishClip){ 
   gotoAndStop(50); 
   } 
 } 

In this example, the curly braces organize the script into two parts. The on(press) handler executes the with statement, then with targets the instance fishClip , sends it to frame 50, and stops it.

 

Tip  

Statements within curly braces are often referred to as blocks of a script. This often makes it easier to refer to a specific portion of the script, for example "the with block."

Parentheses

Parentheses are used in ActionScript to assign arguments for functions or to set the order of operations in an expression. For example, the duplicateMovieClip() function has three arguments: target, instance, and depth . Here you use the parentheses to list the arguments after calling the action:

 duplicateMovieClip("alien","alien_copy",1); 

This statement duplicates (makes a copy of) the clip alien , names the duplicate alien_copy , and sets it at a depth of 1 above the original.

You can also use parentheses to alter the order of operations. The expression 2 + 3 * 4 evaluates to 14, whereas the expression (2 + 3) * 4 evaluates to 20 because the parentheses force you to do the addition first.

Semicolon

In ActionScript, the semicolon ( ; ) is used to mark the end of a statement. For example:

 on(release){ 
   introClip._visible=0; 
 } 

Here, the statement that makes the instance introClip invisible is terminated with a semicolon. If you forget to use the semicolon, Flash will still compile the script correctly. However, it is good practice to follow correct syntax conventions and always terminate statements with the semicolon character.

Semicolons are also used to separate the parameters in a for loop structure. To learn more about this ActionScript convention, see the "Conditionals" section later in this chapter.

Other ActionScript Syntax Conventions

Aside from the mechanics of ActionScript, there are a few other conventions that are important to understand so that you can work flexibly with the language. Certain terms in the language are "protected" or reserved because they have a specific meaning in ActionScript. Other terms must follow a specific upper- or lowercase structure so that Flash will know how to interpret them.

Constants

Constants are terms or properties that retain a specific and unchanging value in ActionScript. In a script, they are written in all-capital letters . Constants are part of three ActionScript objects: the Key object, the Math object, and the Number object.

The following script uses the Key object to test whether the spacebar has been pressed:

 if(Key.isdown(Key.SPACE)){ 
   laser.shoot(1); 
 } 

The spacebar has a constant value, and it is a property of the Key object. When it is pressed, the statements below it execute.

In the next example, the Math object uses the constant value of PI to evaluate the area of a circle:

 area=Math.PI*(radius*radius); 

In the following example, the MAX_VALUE constant is used to set the variable duration to the highest possible value in ActionScript:

 duration=Number.MAX_VALUE; 

Keywords

Keywords are ActionScript terms that are reserved and have a specific purpose in the language. These terms are used only in a specific context and are not available as names of variables, functions, objects, or instances. See the following for a list of ActionScript keywords.

break

case

class

continue

default

delete

do

dynamic

else

extends

for

function

get

if

implements

import

in

instanceof

interface

intrinsic

new

on

onClipEvent

private

public

return

set

static

switch

super

this

typeof

var

void

while

with

ActionScript Case Sensitivity

For the most part, ActionScript is fairly forgiving when it comes to upper- and lowercase letters. If you are scripting in Expert mode, you will notice that the color for a term will change if it isn't entered in the preferred upper- or lowercase syntax. For example, stop() is usually colored blue. If you were to enter it as Stop() (note the capital S), it would change to black. However, in most cases, Flash would still be able to interpret your script without error. To be safe, it is best to follow proper ActionScript syntax at all times; capitalize anything that should appear in uppercase, and keep all lowercase terms free of capital letters.

 New to MX 2004      The release of ActionScript 2 and Flash Player 7 slightly changes the rules of case sensitivity for programs written in ActionScript. Now, movies published for Flash 7 Player will implement case sensitivity. This means that names of functions, keywords, variables, objects, and so on will be held to strict case sensitivity. For example:

 var count=0; 
 var Count=0; 

Here, a Flash 7 movie would consider these to be two different variables: count (with a lowercase first letter) and Count . Similarly, the following statement, which would cause errors in Flash 6 and below, is acceptable in Flash 7:

 sound =  new  Sound(); 

Correct syntax demands that the constructor function for a Sound object use a capital S for the word sound. In Flash 6, where case sensitivity was looser, sound and Sound were interpreted as the same thing, so this statement produces an error. However, because Flash 7 uses strict case sensitivity, sound and Sound are considered to be different and there is no error. While this technique will work in Flash 7 movies, it is strongly discouraged because it can lead to a world of confusion. The following statement exemplifies a better way to create a Sound object:

 mySound =  new  Sound(); 

This is probably somewhat confusing if you are new to ActionScript and programming in general, so the bottom line is this: Follow good practices and use the correct syntax at all times. If you are consistent and adhere to the rules, these issues can be avoided. Keep reading to explore these practices further.

 

Learning ActionScript Language Elements

So far, you have learned the conventions of ActionScript and how the pieces of the language fit together to create scripts. Now it's time to look at those individual pieces and see exactly what ActionScript is made of. There are many components to the language, some of which will seem familiar based on what you already know. Luckily, most of the terms resemble a word in the English language that is near the term's meaning in ActionScript. This (hopefully) makes the terms easier to remember. The most important step toward learning to write ActionScript is understanding the role a particular term plays in the language. As the duties of these terms become clearer, you will begin to see how to fit pieces of the puzzle together to suit your needs.

Data Types

As you learned earlier, data types define the kind of information that can be represented by elements of ActionScript. There are six types of information used in a script: string, number, Boolean, object, Movie Clip, and undefined. We will discuss the specifics of each type.

Strings

Strings are literal chunks of information that hold a textual value. They are composed of any combination of letters, punctuation, and numbers . String data is enclosed in quotes (" " or ' ') and treated as a single piece of information. Because strings are literal, they are case sensitive, so for instance, the strings "one" and "One" are different. In the following example, Joe is a string stored in myName :

 myName="Joe"; 

Strings can be combined, or concatenated , to link string information together. For example:

 fullName=myName+" Smith"; 

The addition operator (+) is used to concatenate string data. Note that in the preceding example, the string " Smith" contains a space. This is to prevent the two string elements from getting closed up when they are concatenated. When the strings are combined, fullName will contain the string 'Joe Smith'.

Strings can also be organized alphabetically by using the comparison operators: < , > , =< , and >= . Flash uses the Latin 1 character set. When evaluating strings alphabetically, the letter z holds the highest value, while A holds the lowest . Note the following expression:

 "alligator"<"zebra"==true 
 "alligator">"Zebra"==true 

Here you can see how lowercase letters hold a higher value than uppercase ones. For more information on operators and comparisons, see the "Operators" section later in this chapter.

Numbers

Numbers are characters that hold a specific numeric value. In ActionScript, number values can be manipulated in expressions using mathematical operators such as addition (+), subtraction ( “), multiplication (*), division (/), modulo (%), increment (++), and decrement ( “ “). You can also use ActionScript's predefined Math object to evaluate numbers and expressions. For more information on this, see the "Operators" section later in this chapter or the ActionScript Reference on this book's accompanying CD.

Booleans

A Boolean is a value that is either True or False. Booleans are used in conditional statements to evaluate script elements and see if values have been met or initialized . The following statements evaluate whether or not all of a movie's frames have been loaded into memory:

 if(_framesloaded==_totalframes){ 
   introMovie.gotoAndPlay(2); 
 } 

If the current number of loaded frames ( _framesloaded ) is equal to the total number of frames ( _totalframes ), the statement inside the parentheses returns a Boolean value of True. If not, it returns False. In most conditional statements, the Boolean value is returned by an expression and not tested explicitly in the if statement. For more specifics on this, see the "Conditionals" section later in this chapter.

Objects

An object is a collection of information organized into properties. These properties have names and values that can be accessed in a Flash movie. The object data type allows you to manipulate the properties assigned to a particular object. In the following statement, the object money has a property named myAccount , which is assigned the value 5000 :

 money.myAccount=5000; 

Flash allows you to create your own objects or use one of the built-in objects such as Date, Array, and Color.

Movie Clips

Movie Clips are self-contained animations that run independently in a Flash movie. They are self-contained because they have their own Timeline. Movie Clips have properties such as alpha or rotation that can be assigned values in ActionScript. Here, a Movie Clip instance is rotated to 180 degrees:

 spinClip._rotation=180; 

Movie Clips also have methods that you can use to control them. In this example, a clip is instructed to stop on the first frame of its Timeline:

 audioClip.gotoAndStop(1); 

 

Tip  

Movie Clips are one of the most interesting, complex, and useful data types in a Flash movie. In fact, they're so important, we've dedicated an entire chapter to them. See Chapter 19 for more details on Movie Clips and their role in Flash.

Undefined

Undefined exists to represent a lack of data, or no data. A variable that has no value returns undefined . A variable with no value cannot be considered an "empty" variable. Without a value, it does not exist and is therefore undefined. For example, the following statement returns nothing; as a nonexistent container, the variable is declared but has no value:

 var one; 

Here, one is undefined and is relatively useless to you. On a related note, if you want to create an empty variable, you can set the value of the variable to be null . Rather than not existing at all ( undefined ), the variable exists but has an "empty," or null value.

The next statement returns null; the variable is an empty but existing container:

 var two=null; 

If you want to erase a variable's value, or create a variable and make it empty, null is a very helpful term. To learn more about variables, see the next section.

Variables

Variables serve as storage locations for information that you need in a script. Variables are like pockets where you can put something, keep it there for a while, and then retrieve it when it's needed again later in your movie. To use a variable, you have to first declare , or state, the variable. Then you must initialize the variable to let Flash know that you are going to store something in it. Once you have initialized the variable with a starting value, it will hold that value until it is changed. To change the value of a variable, all you have to do is add to it, subtract from it, or reinitialize it.

Variables can be used to hold any type of data: string, number, Boolean, object, or Movie Clip. For example, the variable x can be initialized to either a numeric value or a set of string data:

 x=24; 
 x="myName"; 

Variables can also be used in conditional loops to serve as the loop counter. For example:

 j=2; 
 while(j>0){ 
   duplicateMovieClip(_root.ship,"ship"+j,j); 
   root["ship"+j]._y=_root.ship._y+50*j; 
   trace(" duplicated "+j); 
   j ”; 
 } 

In this example, the variable j is initialized to 2 . Every time it passes through the while loop, it is reduced by 1, or reinitialized until it no longer meets the conditions of the loop. The variable j is also used to help name the duplicated Movie Clips and assign the level of each new clip in the duplicateMovieClip statement. In the next statement, j is used in an expression to position the new Movie Clips at a location that is 50* j pixels away from the original clip. That's a lot of work for one variable! The important thing to realize is that you can use a variable over and over again in your scripts to help perform a variety of tasks .

When you use a variable, it's important to give it an appropriate name. There are a few rules concerning this. First, a variable must be an identifier ”a combination of letters, numbers, underscore (_), or dollar sign character ($). See Chapter 17 for specifics on identifiers. Second, a variable cannot be an ActionScript keyword, and it must be unique within the timeline where the variable was created. It's good practice to name a variable something meaningful that relates to the job it will perform in your movie. If you use a variable to store the name of a visitor to your website, name the variable something like siteVisitor to keep things simple. For example, if visitors enter their names in an input text field, give the field the variable name siteVisitor . This way, any time you want to use a visitor's name, you can just call on the variable, and the name will be available immediately. If you wanted to print a farewell message in the text field goodbye , you would write:

 goodbye.text="Thanks for visiting "+siteVisitor; 

We already mentioned that movies published for Flash Player 7 implement strict case sensitivity. This is especially important to consider when naming variables. Here are a few additional naming strategies you can employ to help ensure consistency:

Lowercase, uppercase       Multi-word names can be more descriptive, but of course a space is not allowed in the names of ActionScript objects and variables. You can work around this by using an uppercase first letter for the any additional words in the name. For example:

 firstSecondThird=0; 

Underscore character       Use the underscore character (_) to separate individual words written in all lowercase, for example:

 first_second_third=0; 

Alphanumeric       Use a combination of letters and numbers to give similar or related variables unique names. For example:

 item1=0; 
 item2=1; 

Whatever method you choose to use, be consistent! It will save you headaches and frustration.

Using the trace() Function with Variables

In the previous conditional loop script example, you might have noted the line that reads trace("duplicated"+j); . trace is a special function of ActionScript that allows you to monitor different elements of your script. In this line, the script will trace the word duplicated and concatenate it with the current value of j . It can be very helpful to use this function because it allows you to track the value of your variables as they change while your script executes.

To use the trace() function, all you have to do is enter the information you want to monitor in the parentheses following trace . When you test your movie, Flash will print all the information you asked it to trace in the Output panel. Anything entered within quotes will be treated as a literal string and appear in the Output window exactly as it was entered. This can be helpful because it allows you to make a label for each item you need to trace. For the example trace("duplicated"+j); , the Output window will print:

 duplicated2 
 duplicated1 

This printout reflects the value of the variable j as it goes through the while loop twice, each time decreasing its value.

Variable Scope

One of the most important aspects of variables is their availability, or scope . A variable's scope determines how it is available to other portions of your movie. Because you use variables to store and retrieve information, having them available is very important. In ActionScript, variables have a scope that is global, timeline-specific, or local.

If a variable is global, it is shared by all Timelines in your movie and is available at any time. Any script in any part of your movie can access or change the value of a global variable. You declare a global variable by using the reference global . For example, this statement will create a global variable named store1 and initialize its value to 1:

 _global.store1=1; 

The value of store1 can be retrieved at any point in your movie with this statement:

 trace(store1); 

Because the variable is global, it is always available, by name.

A Timeline-specific variable is also available throughout your movie. However, you must always use a target path when working with the variable; otherwise , Flash won't know where to find the information the variable is storing. Declare a Timeline variable by giving it a name and assigning it a value. For example, to create a Timeline-specific variable named store2 , you would enter the following statement on any Timeline (Movie Clip, main Timeline, and so on):

 store2=2; 

If you created this variable on the main Timeline, its value could be retrieved at any point in your movie with this statement:

 value=_root.store2; 

If you created store2 on the Timeline of the Movie Clip instance sprocket , you would access it by using this target path:

 value=_root.sprocket.store2; 

Because the variable is scoped to a particular Timeline, you must refer to it using a target path, or the "address" of the variable in your movie.

A local variable is different. Local variables are scoped to functions and can be changed only within the block of script or function where they reside. This can be helpful if you have a value that needs to exist for only a very brief period of time. To make a variable local, you must use the var action when you declare and initialize the variable. For example:

 function init3(){ 
   var store3=3; 
 } 

This script declares the variable store3 as a local variable and initializes its value to 3 . As a local variable, store3 is available only within the curly braces ( {} ) of the function where it resides, and it will be " alive " (contain a value) only while the function is executing. To summarize:

§                       To create a global variable, type _global.name= and assign a name and value.

§                       To create a Timeline-specific variable, type the name of the variable and use the assignment operator ( = ) to assign a value.

§                       To create a local variable inside a function, type var , followed by the variable name, and use the assignment operator ( = ) to assign a value.

Operators

Operators are used to produce values. They are characters that instruct ActionScript how to combine, remove, or compare the values in an expression. On both sides of the operator, you have the values, known as the operands . The operator takes the operands, performs its function on them, and leaves a final value for the expression.

If there is more than one operator in an expression, they are executed in a specific order, which Macromedia calls precedence. Operators with the highest precedence are executed first, followed by others in order of highest to lowest precedence. For example:

 total = 3 + 4 * 5 
 total = 23 

According to the rules of precedence, the 4 and 5 are multiplied first, and then the 3 is added. Tables 18.1 “18.4 list some of the ActionScript operators in order of precedence, from highest to lowest. Where operator precedence is equal, operations are performed from the left to right.

Numeric Operators

Numeric operators are used to add, subtract, multiply, and divide the operands of an expression. Table 18.1 lists the ActionScript numeric operators. Operators with the highest precedence are listed first; precedence decreases as you move down the table.

Table 18.1: The Numeric Operators

Operator

Operation

++

Increment by one

“ “

Decrement by one

*

Multiplication

/

Division

%

Modulo

+

Addition

Subtraction

Comparison Operators

The comparison operators are used to compare the value of two operands and return a Boolean (True or False) value based on the comparison. Table 18.2 lists the ActionScript comparison operators. Comparison operators have equal precedence and are read from left to right.

Table 18.2: The Comparison Operators

Operator

Operation

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

Logical Operators

Logical operators are used to compare two Boolean values and return a third Boolean value. LogicalAND will evaluate to true if all conditions are true. LogicalOR will evaluate to true if one of the conditions is True and false if all conditions are False. LogicalNOT inverts the value of an expression ”for example, !false==true . Table 18.3 lists the ActionScript logical operators. Operators with the highest precedence are listed first; precedence decreases as you move down the table.

Table 18.3: The Logical Operators

Operator

Operation

!

LogicalNOT

&&

LogicalAND

LogicalOR

Equality and Assignment Operators

The equality operators are used to test for equality between two operands. The operation will return a Boolean value based on the operands. The assignment operators make assignments and initialize variables. Table 18.4 lists the equality and assignment operators. Operators with the highest precedence are listed first; precedence decreases as you move down the table. All compound assignment operators (+=, “=, *=, and so on) have equal precedence and are read from left to right.

Table 18.4: The Equality and Assignment Operators

Operator

Operation

==

Equality

===

Strict equality

!=

Inequality

!==

Strict inequality

=

Assignment

+=

Addition and assignment

“=

Subtraction and assignment

*=

Multiplication and assignment

/=

Division and assignment

%=

Modulo and assignment

 

 

Tip  

ActionScript's bitwise operators, which are used to set and evaluate values at the bit level, are beyond the scope of this book and will not be covered. To learn more about them, refer to the documentation that ships with Flash.

ActionScript's Global Functions

The ActionScript language incorporates many built-in, or global, functions. These functions are part of the language and are used to perform many of the more common, frequently needed tasks in a Flash production. In the past, Macromedia referred to these global functions as actions . This term seems to have gone out of favor. Ultimately, this is good, as the term actions was not really appropriate in a computer language such as ActionScript. Whatever you prefer to call them, the global functions are statements in ActionScript that issue commands to a movie or one of its components, telling it to do something. For example:

 gotoAndPlay(5); 

The gotoAndPlay() function tells the current timeline to go to frame 5 and continue playing when it gets there.

Here's another example:

 duplicateMovieClip("myClip","myOtherClip",1); 

This action makes a copy of the Movie Clip myClip , names the copy myOtherClip , and sets it at stacking level 1 above the original clip.

Global functions are one of the largest portions of the ActionScript language. They can be found in the ActionScript Toolbox section of the Actions panel. Click the Global Functions icon to display a list of categories. Each contains a set of functions that are available to you.

Conditionals

In the preceding chapter, you learned about the flow of scripts. Conditionals are used to direct this flow. Conditionals are statements that present a script with a condition to be tested. The test returns a Boolean value, either true or false . Depending on this outcome, the script is routed in the appropriate direction by the conditional structure. In ActionScript, the main conditionals are if , if...else , switch , while , do...while , and for .

"if" and "if else" Statements

Statements that test whether a condition evaluates to either true or false use the if statement. ActionScript evaluates the condition in the first line of the script and then proceeds to execute the appropriate statements that follow, based on the condition's evaluation. For example:

 if(y<_currentframe){ 
   move=Math.PI*y; 
   saucerClip._x=saucerClip._x+move; 
 } 

In this script, if the statement y<_currentFrame evaluates to true , the following statements within the curly braces are executed. If it evaluates to false , the code in the if block is skipped and execution of the script skips to the first statement after the closing curly brace of the if block. if conditionals can have alternative statements as well. The preceding example could be expanded as follows:

 if(y<_currentFrame){ 
   move=Math.PI*y; 
   saucerClip._x=saucerClip._x+move; 
 }else{ 
   gotoAndPlay(1); 
   y++; 
 } 

This second script has an else block. This means that if the y<_currentFrame statement evaluates to false , the statements following }else{ are executed as an alternative.

Simplifying if...else with the switch Statement

The switch statement is a newer conditional structure that provides an alternative to if...else statements. This conditional structure presents a script with a series of cases, each of which will be executed depending on the value of the condition to be tested. Consider the following statements:

 num=1; 
 switch(num){ 
   case 1: 
   trace("case 1 was true"); 
   break; 
   case 2: 
   trace("case 2 was true"); 
   break; 
   case 3: 
   trace("case 3 was true"); 
   break; 
   default: 
   trace("no case was true") 
 } 

In the preceding switch statement, the value of num is tested over several conditions, or cases. If a case returns true , meaning that the value of the case equals that of the variable running through the conditional, its statements are executed. In this example, the Output panel would print "case 1 was true" because the value of num happens to be 1. If the first line read num=3 , you would see "case 3 was true" in the Output panel. If no cases evaluated as true , the default case's statement(s) would be executed.

Notice that within each case statement, there is a break action. This ensures that only a single condition's statements are executed. If you ran this script but removed break , it would print the following:

 case 1 was true 
 case 2 was true 
 case 3 was true 
 no case was true 

break causes a script to quit executing statements in the current block. This is defined by the pair of curly braces ( {} ) that contain the switch statement's case conditions. Without the break statement, the remaining conditions in the body of the switch statement will be evaluated as true .

Looping Scripts with Conditional Statements

ActionScript conditionals can also be used to loop repetitive tasks that perform an action or actions a certain number of times. A loop is created with either the while , do...while , or for action. Each of these loop structures has some kind of counter that monitors the number of times the loop should be executed. Generally, the counter is initialized as a variable at the outset of the loop and is either decremented or incremented (decreased or increased by one) with every loop cycle. The function of each loop structure is identical, but the way each performs its function is unique.

The while loop establishes a condition and then executes statements within the curly braces until the condition is no longer true. In the next example, the variable k is used as the loop counter and is decremented each time the loop statements are executed. This loop will execute three times:

 k=3; 
 while(k>0){ 
   duplicateMovieClip("spotClip","spot"+k,k+1); 
   k--; 
 } 

The do...while loop executes its statements first and then tests the condition to see whether the loop should continue. If the condition evaluates to true , the loop continues. With this kind of loop, the statements are always executed at least once, even if the condition is false . For example:

 k=3; 
 do{ 
   duplicateMovieClip("spotClip","spot"+k,k+1); 
   k--; 
 } while(k>0); 

The for loop puts all of the necessary loop information in the first statement: the counter initialization, the condition, and the count expression. For example:

 for(k=3;k>0;k--;){ 
   duplicateMovieClip("spotClip","spot"+k,k+1); 
 } 

Here you can see that the loop conditions and the count are the same as in the while and do...while examples. However, all of the information to establish and control the loop has been economically placed in the first line of the loop.

Another loop structure, for...in , is used to loop through the properties or nested objects of an object. This action can modify properties or use methods to control multiple nested Movie Clips or multiple objects. To learn more about for...in loops, see Hands On 5 and the ActionScript Reference on this book's accompanying CD.

Custom Functions

In the preceding chapter, functions were presented as doers and information processors. You call them or give them a set of arguments, and they perform a specific task using those arguments. ActionScript's global functions are powerful, but limited to an array of prescribed routines for common tasks. You can exercise this same kind of power for tasks of your own. ActionScript allows you to create custom functions. These can be very useful if you have a series of tasks or operations that have to be performed over and over again in your movie. For example, if you need to frequently scale a Movie Clip to 50 percent of its original size, you can write a function. Rather than having to use both the xscale and yscale properties every time you want to scale a clip, you can call on the function and it will do all the work for you.

First, you must define the function. The syntax for defining a function is as follows:

 function  functionName(arguments){  
    statement(s);  
 } 

Here is a function named Half that reduces the horizontal and vertical scale of a Movie Clip by 50 percent and moves it 100 pixels up and to the left:

 function Half(myClip) { 
   
   myClip._x-=100; 
   myClip._y-=100; 
 myClip._xscale=50; 
   myClip._yscale=50; 
 } 

In this function, the term myClip is used as an argument. When the function is called, the Movie Clip listed within the parentheses (an argument to the function) will be scaled down accordingly . When you create a function, it's best to put the script that declares the function in a frame at the beginning of your movie. If ActionScript hasn't read your function, it won't know what to do when you call it later.

 

Note  

When creating a function, it is essential to give it a unique name within your movie so that there is no confusion between functions, variables, and instances. For example, if you had a function named Half and a variable named Half , you would open the door to possible error and confusion with the ActionScript in your movie. If you can't use any other name, append the name with a prefix such as funHalf for the function and varHalf for the variable.

Once you've created the function, you are free to call it whenever you need it in your movie. A function can be called in any script or in any handler, and from any level or Timeline of your movie. Here is an example where the Half function is called when a button is clicked and released:

 on(release){ 
   root.Half( invaders .rogue_1); 
 } 

In this script, the clip rogue_1 (nested inside the clip invaders ) is moved and sized down by 50 percent using the Half function. The target path to rogue_1 is passed as an argument to the function, and the clip is scaled. Because the Half function was created on the main Timeline, it is necessary to include the target reference root when the function is called from a different Timeline.

Objects

Objects are one of the many data types in Flash, and as such, they can be referred to directly in an ActionScript statement. They are also an important element of the language because they hold chunks of information that affect different elements of your movie. Objects have properties that can be set and reset as needed within a movie. They also have methods, which are built-in functions specific to each object, and can be used to produce values or perform tasks.

For a list of the predefined objects in ActionScript, consult the Actions panel (F9). Look for the category named Built-in Classes in the ActionScript toolbox (see Figure 18.1). You can double-click the icon beside each Object to reveal the properties and methods that belong to it. For specifics on each class, chooose Help panel (F1) ActionScript Reference Guide Using the Built-in Classes Overview of Built-in Classes.

click to expand
Figure 18.1: The names, properties, and methods of ActionScript's predefined objects are in the Built-in Classes category of the Actions panel.

 

Inspirational Design Model

For an example of the kind of interactive depth and interest that Flash can create, take a look at Andy Foulds Design: www.foulds2000.freeserve.co.uk/index_v2.html (see Figure 18.2). This site features an interesting blend of text, imagery, animation, and interactivity, much of which takes place in three dimensions. Follow the links Web Design Samples to see his work. In addition to Andy's professional work, check out his Flash samples. These "studies" present all kinds of interesting menu designs and compelling imagery.

click to expand
Figure 18.2: Andy Foulds is a photographer and web designer.

 



Flash MX 2004 Savvy. Also Covers Flash Professional.
Flash Mx2004; Also Covers Flash Professional; Savvy
ISBN: 0471789151
EAN: 2147483647
Year: 2003
Pages: 54

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net