Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 1

Summar y

This chapter serves as a brief introduction to the IDE. The IDE has many facets that you will discover and use. You might wonder why these weren’t covered, but this book focuses on ActionScript and it is the intention of this chapter to introduce you to the IDE so that you can begin and complete the exercises throughout the book. In each example you’ll see small shortcuts and work flows that weren’t covered here. Keyboard shortcuts can speed your work a great deal, and each operating system has slightly different keyboard shortcuts. If a shortcut encountered in the book doesn’t seem to be working, try using the manual menu system to find the action. In most cases, the keyboard shortcut is listed right next to the action in the menu system. Additionally, Appendix B is all about keyboard shortcuts.

The Flash IDE is extremely malleable. You may find that the work flows presented here are completely foreign to your method of working. Because the IDE is so flexible, I encourage you to deviate when possible and explore the IDE to see what it is capable of. The IDE also runs on basic settings files found in the application settings folder on your operating system. Sometimes if you wish you had a particular option, or could remove or simplify an aspect of the IDE, it isn’t difficult to go poking around the Application Settings to see what you can find.

Exercises

1.Create a new FLA (Macromedia Flash document) by selecting File New and choosing Flash Document from the New Document panel. Create a Layer, and place a vector drawing or image object onto the stage. Place a simple Hello World ActionScript on the frame. Rename the layer test and save your FLA. Open a new FLA. Return to your original FLA, right-click (option+click) the frame with the Hello World ActionScript, and select Copy. Paste the frame into your new SWF. Examine the results.

2.Open a new FLA and open the Library. Add a symbol using the panel’s context menu. Add a button or Movie Clip. Double-click the instance you just created and create some graphics within it. Open a new FLA file. Open the new FLA file’s library. Return to the original FLA file’s library and drag the object instance you created to the new FLA. Notice that the symbol now resides in both libraries.

3.Open multiple FLA files. Move between the FLA files by using the tab system at the top of the IDE. Minimize or un-maximize one of the FLA files. Note how the IDE enters a collapsible window mode.

18

2

Getting Star ted with

ActionScript 2.0

Computers are dumb; they cannot think for themselves — they can only follow instructions. Computers are also very precise, so they must be told in exact terms what needs to be done. The purpose of a programming language is to provide you with a means of clearly and accurately telling the computer what you want it to do. ActionScript provides this structure in a way that you also can read and understand.

This chapter gets you started learning ActionScript syntax and structure by introducing the statement and the variable. Do not worry about memorizing each fact and concept that’s covered in this chapter. The more actual examples you try for yourself, the more comfortable you will become with ActionScript 2.0.

Understanding Statements

When you write a letter or an email message, you create sentences and string them together to form paragraphs. Each sentence is structured of verbs, nouns, adjectives, and other elements of the English language, and each sentence expresses one discrete message. Similarly, writing code is a process of creating individual statements that communicate to Flash one discrete task that you want it to perform. A sequence of statements spells out how to perform a larger task in detail, much like sentences are strung together into paragraphs to explain a larger idea.

Using Simple Statements

The building block of ActionScript coding is the simple statement, generally just referred to as a statement. Each statement represents one distinct operation that is to be performed. Sequences of statements are executed one after another in the order that they appear.

A statement is generally represented by a single line of code. It consists of a combination of keywords, variables, and operators, and terminates with a semicolon (;). Don’t worry about the details of what’s on each line right now; just take the high-level view of them.

Chapter 2

One statement might perform a mathematical calculation and save the result for future use:

position = 350 / 2;

Another might move an onscreen element to a new position:

helicopterClip._x = 25;

Yet another might open a Web page in a new browser window:

getURL(“http://www.apple.com/ipod/”, “externalWindow”);

Usually a statement cannot run until the previous one has completely finished. In the following example, the first statement calculates a value and saves it temporarily, and then the second statement makes use of that value to position an onscreen element:

position = 350 / 2;

helicopterClip._x = position;

Generally, no statement runs until the previous one is completely finished. The exception to this is loading external media, where calls to load an external file pass to the next statement before the external file has loaded. You learn more about this beginning in Chapter 7.

Using Compound Statements

Compound statements are composed of multiple statements. Curly braces surround everything that is part of the compound statement. Here’s an example:

if (position < 500)

{

position = position + 10; helicopterClip._x = position;

}

Without worrying too much about the details, both of the statements or neither of the statements between the brackets will run, depending on the outcome of the if statement.

Understanding Operators

Each statement consists of a certain amount of code grammar that defines what that statement does. Relating back to the sentence analogy, a simple sentence might consist of two nouns, or targets of an action, and a verb, or action. The sentence “Marie is given a ball” basically consists of two nouns (Marie and ball) and a verb that describes the interaction (is given). An operator is akin to a verb in that it describes an action, an interaction, or a relationship. Here’s an example:

mariesToy = “ball”;

20

Getting Started with ActionScript 2.0

This line contains two “items” that can interact. The first, mariesToy, is a container for data (called a variable) and the second, “ball”, is data that can be placed within that container. The = symbol is the equals operator, which invokes the action of assigning whatever is to the right of the = symbol to the variable on the left of the symbol.

Multiple operators can be used in the same statement. For instance, the following line adds a value to whatever value is already in the numToys variable:

numToys = numToys + 1;

If you are a mathematician, your head might be spinning because this is not a correct math formula. But it isn’t a math formula, and if you think in terms of the operators that are at work, you see that this works just fine. The first operator that is evaluated is the +. It grabs the number to its right, retrieves the value contained of numToys, and adds the two. Next, the = operator is evaluated; it assigns the result of the addition back to numToys. If numToys initially held the number 1, it now holds the number 2.

Not all operators require items on both sides of the operator. The increment operator (++), for example, is shorthand for adding 1 to a container, and it only needs a container on its left:

numToys++;

This operator retrieves the number held by numToys, adds one to that number, and then assigns the new number back to the numToys container. If numToys holds the value 3 before this line executes, it holds the value 4 afterward.

You can use a number of mathematical operators, including addition (+), subtraction (-), multiplication (*), division (/), and remainder/modulo (%). Take a look at the following example:

a = 6; b = 4; c = 2;

calculationResult = a + b - c; // calculationResult contains 8 calculationResult = a / b; // calculationResult contains 1.5 calculationResult = a % b; // calculationResult contains 2

The first three lines assign numbers to variables, which are discussed later in this chapter. The next three lines use mathematical operators to calculate new values and to assign those values to another variable.

The modulo (%) operator returns the remainder of a division. In this example, 4 divides into 6 once, with a remainder of 2, so the modulo operator returns 2.

A series of calculate-and-assign operators act as shorthand for some common mathematical operations. The following two lines of code, for example, are equivalent:

a = a + 2;

a += 2;

The first line adds the value already stored in variable a and the number 2, and then assigns the new value back to a. If a stored the value 7 before this line runs, it stores 9 afterward. The second line does the same thing, but performs the addition and the assignment in one step. The same convention applies

21

Chapter 2

with the subtract and assign (-=), multiply and assign (*=), divide and assign (/=), and modulo and assign (%=) operators. In general, these shortcut operators provide a convenient notation for simple cal- culate-and-assign operations, but there’s nothing holding you back from using the a = a + 2; syntax if you prefer.

Not all operators perform assignments or calculations. For instance, the round bracket operators — () — are used to clarify a statement and to force the order in which the operators are evaluated. The following two statements, for example, return different results:

result = 6 + 4 * 2; // result contains 12

result = (6 + 4) * 2 // result contains 20

In the first line, the * operator takes precedence over the + operator, so 4 * 2 is calculated first, and the result of that is added to 6. In the second line, the brackets create a higher priority, forcing 6 + 4 to be calculated first, and that result is then multiplied by 2.

This last example brings up the issue of figuring out which operator is evaluated first, because they apparently are not evaluated from left to right. Which operators take priority?

Using Operator Precedence

If you are wondering why the + operator in the numToys = numToys + 1; statement is evaluated before the = operator, or why a multiplication operator is evaluated before an addition operator, just know that there is an order to the chaos. Each operator is assigned an operator precedence, which is basically a ranking. The operator with the higher precedence is always evaluated before the operator with lower precedence. This ranking has been worked out by the people who write compiler specifications so that operations flow in a way that produces behavior that works properly and predictably.

When it comes to mathematical operators, the field of mathematics defines its own rules about what calculations are performed first: multiplication and division take place before addition and subtraction, and round brackets take overall precedence. These rules are reflected in the ActionScript operator precedence ranking.

The ranking is shown in the upcoming “Understanding the Common Operators” section.

Exploring Operator Associativity

An operator can act on code that is to its right and can act on code to its left. Which does it do first? That’s where operator associativity comes in. The associativity of an operator means that it either first looks to the left or it first looks to the right. If an operator first looks to the left, it has left-to-right associativity; otherwise it has right-to-left associativity. In an earlier example, you saw the = operator look first to the right for a value to assign, and then assign it to the container on its left, so the = operator uses right-to-left associativity. In the numToys++ statement, the ++ operator started by getting the value on its left. It didn’t actually do anything with the right, but the associativity that it uses is still called left-to- right. The table in the following section includes the associativity for the common operators.

For the most part, you don’t need to care about this too much because the associativity for the different operators has been chosen to make them just work the way you would expect; still, it’s a good idea for you to know the concept to understand how operators work.

22

Getting Started with ActionScript 2.0

Understanding the Common Operators

The following table lists some common operators. They are ranked from the highest operator precedence to the lowest. You learn more about these operators in this and the next few chapters.

Operator

Name

Associativity

Description

 

 

 

 

++

Increment

Left to right

Adds 1 to a number and assigns the new

 

 

 

number back to the variable.

--

Decrement

Left to right

Subtracts 1 from a number and assigns

 

 

 

the new number back to the variable.

[ ]

Array element

Left to right

Accesses an individual element from a

 

 

 

collection of data.

( )

Parentheses

Left to right

Forces the operators within the parentheses

 

 

 

to be evaluated before any operators

 

 

 

outside the parentheses.

-

Negation

Left to right

Inverts the sign on a number. The negation

 

 

 

operator is different from the subtraction

 

 

 

operator only by the context in which it

 

 

 

sits.

!

Logical NOT

Right to left

Converts a false value to true or a true

 

 

 

value to false.

*

Multiply

Left to right

Multiplies two values.

/

Divide

Left to right

Divides the value to the right of the

 

 

 

operator from the value to the left of the

 

 

 

operator.

%

Modulo

Left to right

Returns the remainder of a division of

 

 

 

two whole numbers.

+

Plus

Right to left

Adds two values.

-

Minus

Right to left

Subtracts the value on the right from the

 

 

 

value on the left.

<

Less than

Left to right

Returns true if the value on the left is

 

 

 

less than the value on the right; otherwise

 

 

 

it returns false.

<=

Less than or equal to

Left to right

Returns true if the value on the left is

 

 

 

less than or equal to the value on the

 

 

 

right; otherwise it returns false.

>

Greater than

Left to right

Returns true if the value on the left is

 

 

 

greater than the value on the right,

 

 

 

otherwise it returns false.

 

 

 

Table continued on following page

23

Chapter 2

Operator

Name

Associativity

Description

 

 

 

 

>=

Greater than or

Left to right

Returns true if the value on the left is

 

equal to

 

greater than or equal to the value on the

 

 

 

right; otherwise it returns false.

==

Equal

Left to right

Returns true if the value on the left is

 

 

 

equal to the value on the right; otherwise

 

 

 

it returns false.

!=

Not equal

Left to right

Returns true if the value on the left is not

 

 

 

equal to the value on the right; otherwise

 

 

 

it returns false.

&&

Logical AND

Left to right

Returns true only if both the value on

 

 

 

the left of the operator and the value on

 

 

 

the right of the operator are true;

 

 

 

otherwise it returns false.

||

Logical OR

Left to right

Returns true if either the value on the

 

 

 

left of the operator or the value on the

 

 

 

right of the operator is true; otherwise it

 

 

 

returns false.

=

Assignment

Right to left

Assigns the value on the right of the

 

 

 

operator to the variable on the left of the

 

 

 

operator.

*=

Multiply and assign

Right to left

Multiplies the variable on the left by the

 

 

 

number to the right, and then assigns the

 

 

 

new number to the variable.

/=

Divide and assign

Right to left

Divides the variable on the left by the

 

 

 

number to the right, and assigns the new

 

 

 

number to the variable.

%=

Modulus and assign

Right to left

Retrieves the modulus from the division

 

 

 

of the value on the left by the value on the

 

 

 

right, and assigns the new number to the

 

 

 

variable.

+=

Add and assign

Right to left

Adds the number on the right and the

 

 

 

variable on the left and assigns the new

 

 

 

number to the variable.

-=

Subtract and assign

Right to left

Subtracts the number on the right from

 

 

 

the variable on the left and assigns the

 

 

 

new number to the variable.

,

Comma

Left to right

Delimits repeating items, such as elements

 

 

 

in an array.

24

Getting Started with ActionScript 2.0

Using White Space

The Flash compiler ignores all the white space in your code. This means that the spaces, tabs, and returns in your code have no impact on the compiler. That’s great news because it enables you to adopt a coding style that works well for you, and that is easy to read, just by changing how you use white space in your code.

The following three statements all work, despite the differences in white space:

getURL(“http://www.apple.com/ipod/”,”externalWindow”);

getURL( “http://www.apple.com/ipod/”, “externalWindow” );

getURL ( “http://www.apple.com/ipod/” , “externalWindow” ) ;

Similarly, compound statements can be formatted in numerous ways:

if (position < 500)

{

position = position + 10; helicopterClip._x = position;

}

if (position < 500) { position = position + 10;

helicopterClip._x = position;

}

Short compound statements might fit on one line, although we do not favor that format:

if (position < 500) { helicopterClip._x = position; }

As you learn ActionScript, you will start using compound statements within compound statements. Indenting by using tabs makes that code more readable:

if (position < 500)

{

if (isEnabled == true)

{

position = position + 10; helicopterClip._x = position;

}

}

Whatever style you use, use it consistently.

Many code editors, such as the one built into Flash, have commands for auto-formatting code. Look for the Auto-format button (see Figure 2-1) at the top of the Actions panel or the script file editor.

25

Chapter 2

Figure 2-1

Using Comments

Not every line in your script needs to be executable code. You can place comments throughout your code to either annotate your code or prevent lines of code from being compiled without actually deleting the code. Two types of comments exist: inline and block.

An inline comment is designated by two leading slashes (//). The compiler ignores everything after the second slash until the line break. Inline comments are great for adding short annotations, such as the following:

// TODO: Get rid of the hard-coded string getURL(“http://www.apple.com/ipod/”,”externalWindow”);

helicopterClip._x = 25; // Position of the landing pad.

When you need larger comments, you can use the block comment, which begins with a slash and asterisk (/*) and ends with an asterisk and slash (*/). Everything between /* and */ is ignored by the compiler.

/* Author:

Nathan Derksen

*Creation Date: June 3, 2006

*Change log: June 4, 2006 - Added easing effect to animation */

This is not recommended, though. It’s preferable to use the double-slash syntax at the start of each comment line, and to use the block syntax for “commenting out” sections of code (that is, preventing those sections from being run). If you think about it for a minute, you’ll understand why. The compiler ignores everything after one /* until it reaches a */. If there’s a multiline comment included in that code block, the compiler ignores its opening /* and then begins to try to run the code that follows the comment (the first */ it comes to). If that doesn’t throw an error, one will certainly be thrown when the compiler runs into the second */ — the one at the end of the code block, which, to the compiler, has no starting /* and is therefore out of place. Here’s an example:

/*

if (position < 500)

{

/* TODO: Implement animation of the helicopter

Needs to be done before rest of project can proceed. */ position = position + 10;

helicopterClip._x = position;

}

*/

26

Getting Started with ActionScript 2.0

Here the compiler ignores the if statement and the comment up to the */, and then tries to run the position = statement, and if it gets to the */ at the end of the code block, it throws a syntax error for an out-of-place */. Here’s commented code that works as intended:

/*

if (position < 500)

{

//TODO: Implement animation of the helicopter

//Needs to be done before rest of project can proceed. position = position + 10;

helicopterClip._x = position;

}

*/

The following will work as intended.

Here’s an example that shows a block of code that’s been commented out, preventing all the statements between the /* and */ markers from being run. This usage can be a real boon to debugging because it enables you to isolate code blocks to pin down errors.

/*

if (position < 500)

{

position = position + 10; helicopterClip._x = position;

}

*/

You learn more about good commenting practices in Chapter 5.

Introducing Variables

A variable is simply a way of storing some piece of data for later use. A single variable stores a single chunk of data, with no limit to the size of that chunk. To make space for your data, you declare a variable. The process of declaring a variable does several things:

1.

2.

3.

Requests that space be set aside in main memory (RAM) for some data.

Links that reserved space with a variable name of your choice.

Optionally assigns some initial data to that reserved space.

Declaring a variable is as simple as this:

var myTitle:String;

The keyword var indicates that what is to follow is a variable declaration. The variable name (myTitle, in this example) comes next. The variable name that you choose provides the means of accessing any data stored within the variable from later statements.

27