communicating with actionscript -...

26
2 Communicating with ActionScript Communicating to Movie Clips 15 Modifying Movie Clip Properties 21 Understanding Variables 29 Setting Variable Data Types 30 Using Trace Statements 33 Using Comments 36 In this chapter, you’ll learn how to communicate with different objects in your Adobe Flash CS3 Professional project and even with other people who may be working on the project using ActionScript 3.0. The lines of communication flow both ways; you can use ActionScript to send mes- sages to objects, such as when you transform a symbol instance’s prop- erties, or to provide feedback, such as when you run a trace statement. Alternatively, you can embed comments directly in the code so other people who are working on the same Flash project can read them. Before you start adding interactivity to your Flash movies using ActionScript, you need to learn how to communicate with the objects in them. So, let’s get started! ActionScript 3.0 for Adobe Flash CS3 Professional : HOT 14

Upload: dangliem

Post on 09-Feb-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

2Communicating withActionScript

Communicating to Movie Clips 15

Modifying Movie Clip Properties 21

Understanding Variables 29

Setting Variable Data Types 30

Using Trace Statements 33

Using Comments 36

In this chapter, you’ll learn how to communicate with different objects in

your Adobe Flash CS3 Professional project and even with other people

who may be working on the project using ActionScript 3.0. The lines of

communication flow both ways; you can use ActionScript to send mes-

sages to objects, such as when you transform a symbol instance’s prop-

erties, or to provide feedback, such as when you run a trace statement.

Alternatively, you can embed comments directly in the code so other

people who are working on the same Flash project can read them. Before

you start adding interactivity to your Flash movies using ActionScript,

you need to learn how to communicate with the objects in them. So,

let’s get started!

ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T14

02_AS3HOT_(14-39).qxd 09/12/2007 10:43 AM Page 14

Page 2: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

15Chapter 2 : Communicating with ActionScript

1E X E R C I S E

Communicating to Movie Clips

The first step in communicating with objects is to transform the object into a symbol, a type of predefinedclass, so ActionScript can interact with it. In this exercise, you’ll convert a shape to a movie clip symboland add named instances to the Stage so that later you can call them with ActionScript.

Start Flash CS3. The Welcome screen should appear automatically by default. If you have modifiedyour preferences to hide it, choose Edit > Preferences (Windows) or Flash > Edit Preferences (Mac),and choose Welcome Screen in the On launch pop-up menu in the General category of the dialog box.

Choose Flash File (ActionScript 3.0) under the Create New heading on the Welcome screen.

A new document opens with a blank Stage. Next, you’ll draw a simple object on the Stage and convert it to a movie clip.

2

1

02_AS3HOT_(14-39).qxd 09/12/2007 10:43 AM Page 15

Page 3: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Select the Rectangle tool in the Tools panel. Select a green color in the Fill Color box, and makesure you have the Object Drawing Model button at the bottom of the Tools panel deselected. Click and drag to draw a rectangle on the Stage. The rectangle can be as large or as small as you want.

Select the Selection tool in the Tools panel, or press V on your keyboard. Click and drag a selectionarea around the rectangle to select the entire object.

You will know the rectangle is selected by the mesh that appears over the object when it is selected.

4

3

16 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

The dotted meshindicates the shape

is selected.

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 16

Page 4: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Choose Modify > Convert to Symbol or press F8 on your keyboard to open the Convert to Symboldialog box.

Type mcRectangle for the symbol name,and choose Movie clip for Type. Leave theRegistration setting in the upper-left corner,and click OK.

Now the shape on the Stage has been converted to an instance of the new symbol, and the symbol itselfappears in the Library panel. If the Library panel is not open, choose Window > Library or press Ctrl+L(Windows) or Cmd+L (Mac) to open it.

6

5

17Chapter 2 : Communicating with ActionScript

T I P : Selecting ShapesOrdinarily, you click to select objects on the Stage with the Selection tool, but whenyou are working with merged shapes, you can move and transform the stroke and fillindependently of one another. To make sure you select the entire shape, select theSelection tool, and click and drag a bounding box around the shape or double-clickthe shape’s fill to select both the stroke and the fill.

N O T E : Symbol Naming ConventionsAs you start creating symbols and instances, you’ll need to name them. In more com-plex Flash projects that include ActionScript, instance names become important,especially for movie clip symbols. For this reason, you need to adhere to some guide-lines when naming symbols, instances, and document files in Flash CS3. Followingthese rules will keep you out of a lot of trouble.

Do use the following:

Lowercase letters (a–z) for the first character: Symbol names starting with numbersor uppercase letters can confuse ActionScript. For this reason, start symbol nameswith a lowercase letter. You can use numbers (1–9) for symbol names but not as thefirst character. Restricting your names to only lowercase letters makes them easier toremember.

Descriptive names: Try to use descriptive, easy-to-remember names. For example,use mcRectangle rather than symbol6. When using multiword names, capitalize thefirst letter of each word (except the first word) so you can read it easier. However, youmust remember that when you refer to an object in ActionScript, you reference thesymbol with the same capitalization you used in its name.

Don’t use the following:

Special characters: Special characters (such as !, @, #, &, $, and many others) are for-bidden. Many of these special characters have a specific meaning to Flash CS3 andcan cause problems with ActionScript. To avoid accidentally using a special character,avoid everything but numbers and letters.

continues on next page

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 17

Page 5: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Deselect the symbol instance by clicking the gray artboard around the Stage. Choose Window >Properties > Properties to open the Property inspector, if it is not already open. Click to the reselect therectangle on the Stage, and then look in the Property inspector to examine the rectangle’s properties.

The Instance Behavior pop-up menu in the upper-left corner should say Movie Clip, and the InstanceName field should have the <Instance Name> placeholder text, as in the illustration shown here. To communicate with the movie clip in ActionScript, you must assign every symbol instance an instancename. That’s the next step!

Type rectangle_mc in the Instance Name field.

Instance names should follow the same naming conventions as symbol names. To avoid confusion, don’tuse the same name for a symbol and one of its instances. In this case, you’re just inverting the two partsof the name, separated by an underscore. The _mc part actually has a special significance, as you’ll dis-cover in Exercise 2.

Select the Free Transform tool in the Tools panel, or press Q on your keyboard.9

8

7

18 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

N O T E : Symbol Naming Conventions continuedSpaces: Never use spaces in your names. Instead, string your words together, or useunderscores. For example, instead of my first symbol, use myFirstSymbol or, evenbetter, my_first_symbol (no uppercase letters to remember!).

Periods: Never put periods in your file or symbol names (other than the three-letterextension). For example, snow.boarder.fla will cause problems. Instead, usesnow_boarder.fla.

Forward slashes: Forward slashes are misinterpreted as path locations on a harddrive. Never use them. For example, my/new/symbol would be interpreted as theobject symbol located in the new folder located in the my folder.

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 18

Page 6: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Eight handles will appear around the edges of the shape. Position your cursor over one of the out-side corners, and then click and drag to rotate the shape. Click and drag any of the handles on the sidesof the shape to make the shape larger or smaller.

In the Library panel,click and drag themcRectangle symbol tothe Stage to add anotherinstance to the document.Click and drag to add athird instance to theStage.

11

10

19Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 19

Page 7: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Select the Selection tool, and select one of the mcRectangle instances on the Stage. Go to theProperty inspector, and choose Tint in the Color pop-up menu. Click the Fill Color box, and choose ablue color to tint the rectangle. Type 30% in the Tint Amount field.

Now you have three instances of the original symbol on the Stage. As most Flash users know, no matterhow you modify the instances, the original symbol will remain the same until you choose to modify it.

You’ll learn how to change instance properties, including size, rotation, and tint, using ActionScript in thenext exercise. The critical part to remember from this exercise is that you won’t be able to do so, or com-municate with the instances at all, unless you assign them each a valid instance name. The instance nameis what differentiates the objects from one another.

Now you have one named instance of mcRectangle on the Stage. In the next exercise, you’ll dive intoActionScript and learn how to modify some of its basic properties.

12

20 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 20

Page 8: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

2E X E R C I S E

Modifying Movie Clip Properties

In this exercise, you’ll learn how to modify a movie clip’s properties with ActionScript. Properties areattributes of an object, such as color or size, that you can also modify in the Property inspector in Flash.

Copy the chap_02 folder from the ActionScript HOT CD-ROM to your desktop. OpenMovieClip_Properties.fla from the chap_02 folder.

Select the Selection tool in the Tools panel. Click the blue rectangle on the Stage, and go to theProperty inspector.

Notice that for this particular object you can modify the following properties: the width, the height, theobject’s position on the Stage (via the X and Y values), the color, and the blending mode for the object.The properties in the Property inspector will change depending on the type or class of object selected.

2

1

21Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 21

Page 9: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Change Height to 125,and watch the rectangle on the Stage get taller.

Change the X position to145, and watch the rectanglemove to the left.

You can also change propertiesof objects on the Stage usingthe tools in the Tools panel.

4

3

22 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 22

Page 10: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Select the Free Transformtool in the Tools panel. Selectthe same rectangle, and rotateit counterclockwise to watchthe position properties in theProperty inspector change.

Press Ctrl+Z (Windows) or Cmd+Z (Mac) to undo the shape rotation.

Now that you understand how you can change properties by modifying the shape on the Stage, you willmodify the properties through ActionScript. However, first each of these objects needs an instance name.

Press V to switch to theSelection tool. Select the blue rectangle. Choose theProperty inspector, andchange the instance name torectangle1_mc.

Select the rectangle in the upper-right corner of the Stage. Go to the Property inspector, and typerectangle2_mc in the Instance Name field. Choose the last rectangle, which has already been namedrectangle_mc, and change the instance name to rectangle3_mc.

8

7

6

5

23Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 23

Page 11: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Click the Insert Layerbutton at the bottom theTimeline to create a newlayer. Double-click the nameof the new layer, and typeactions to rename the layer. Click and drag the actions layer to the top of the layer order if it is not already there.

You’re not required to rename this layer. You don’t even need a separate layer for your actions, but it isconsidered best practice. By default, when a SWF files loads, the layers are loaded from the bottom up inthe order they appear in the Timeline. Keeping the actions in a separate layer at the top of the Timelineensures all the objects are fully loaded before the ActionScript tries to run.

Click the dot under the lock icon on the actions layer to lock the layer.

Locking the layer prevents you from accidentally adding contents to the actions layer but still allows youto add ActionScript.

Select Frame 1 on the actionslayer, and choose Window > Actions to open the Actions panel. The keyboard shortcut for this is F9 (Windows) or Opt+F9 (Mac).

The Actions panel has three basicareas: a Script pane, where youtype the ActionScript code; theActions toolbox, which contains alisting of all the classes, theirmethods, their events, and theirparameters; and a Script naviga-tor, which allows you to navigateto the different frames containingActionScript.

The Actions toolbox

11

10

9

24 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

The Actions toolbox

The Script paneThe Script navigator

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 24

Page 12: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

You’ll also see 15 buttons above the Script pane, as shown in the illustration here. You don’t need toknow them all to start coding, but rest assured, you will be using these buttons throughout this book. For now, to start typing code, you need to make sure Script Assist is off. Script Assist is a feature thatprompts you to type code through a form field.

If the Script Assist button above the Script pane is pressed, click it again to turn it off.

In this exercise, you won’t be using the Actions toolbox. Instead, you’ll be typing the code by hand. To make more room to type, you will close this pane, along with the Script navigator.

Click the triangle button in themiddle of the split bar separating theScript navigator and Actions toolboxfrom the Script pane to hide them.

Now you’re ready to code. The firststep is to call the object you want totransform, using the instance name.

13

12

25Chapter 2 : Communicating with ActionScript

Insert a target path

Check syntax

Auto format

Show code hint

Debug options Collapse selection

Collapse between braces

Expand All

Apply block comment

Apply line comment

Remove comment

Script Assist

Add new item

Find

Show/Hide Toolbox

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 25

Page 13: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Insert your cursor on Line 1, type rectangle1_mc, and then add a period.

A pop-up menu will appear containing methodsyou can use with this movie clip object. This isFlash’s code hinting feature. Flash happens torecognize that the object is a movie clip becauseof the _mc extension you added to the instancename and suggests a number of properties andmethods that you can pick from. As I mentionedin Exercise 1, the _mc is optional, but it is handy when it comes time to type your code.

14

26 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

T I P : Turning Code Hinting On and OffCode hinting is just oneof the features of FlashCS3’s code editor; otherfeatures include syntaxchecking, code coloring,and autoformatting. Youcan turn these featureson and off by choosingEdit > Preferences(Windows) or Flash >Preferences (Mac) and selecting theActionScript category.

When code hinting isturned on, the hints disappear as soon asyou finish typing orchoose a selection in the pop-up menu. If you need to access the Code Hint pop-upmenu again, positionyour cursor in the correct location, andclick Show Code Hint inthe Script pane toolbar,the sixth button fromthe left.

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 26

Page 14: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Type al. The Code Hint menu will filterthrough the results for anything that starts withal. (alpha should be the only highlighted entry.)Press Enter (Windows) or Return (Mac), andFlash will complete the rest of the word.

After alpha, press the spacebar, and type the following:

= .5;

Now you are telling Flash that the object’s alpha property, or transparency, should be equal to .5, or 50 percent. The semicolon ends the statement. It’s kind of like a period in a sentence.

If you’re familiar with ActionScript 2.0, you’ll notice two things about this property that are different. One is that the property has been changed from _alpha to just alpha. Second, the range for the alpha is no longer from 0 to 100; it’s from 0 to 1.

Minimize the Actions panel by double-clicking the panel’s tab. On the Stage, select rectangle1_mc.

Notice that the rectangle is still fully opaque. Why? The ActionScript does not come into play until themovie is published, which you’ll see next.

Press Ctrl+Enter (Windows) orCmd+Return (Mac) to test the movie.

There you have it. The rectangle is now semitransparent. To be precise, it’s exactly50% transparent.

Close the movie preview window, and double-click the Actions panel tab to maximize the panel.19

18

17

16

15

27Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 27

Page 15: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Change the first line of code to readas follows:

rectangle1_mc.alpha = .15;

This will make the rectangle even moretransparent. On the scale from 0 to 1, 0is completely transparent and 1 is com-pletely opaque.

Press Ctrl+Enter (Windows) orCmd+Return (Mac) to test the movie again.

The rectangle in the movie is even more trans-parent, but once you close the preview win-dow, you’ll notice that the object on the Stageis still completely opaque.

Close the preview window, and return to the Actions panel.

So now you know how to modify a movie clip’s properties, but you still might be thinking, how am Igoing to remember all the possible values for each property? How will I remember that alpha accepts a value between 0 and 1? Well, Flash has another helpful feature you can use.

22

21

20

28 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

N O T E : Selection Cannot Have Actions AppliedIf you get the message “Current selection cannot have actions applied to it” whenyou open the Actions panel, don’t panic. This simply means you have selected thewrong frame in your Timeline. You must type actions in a blank keyframe. Return tothe Timeline, and select the blank keyframe in your actions layer; the Actions panelwill allow you to type the code again.

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 28

Page 16: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Highlight the alpha prop-erty in the code to select it.Press F1 on your keyboard.

Pressing F1 opens the Helpmenu, which in Flash CS3 iscontext-sensitive, so it opensright to the alpha property.The Help menu contains verydetailed information on all theActionScript properties,including their accepted val-ues. Once Help is open, youcan use the Search field tolook for properties, but I findthe other method a little faster.

When you are finished, close MovieClip_Properties.fla. You don’t need to save your changes.24

23

29Chapter 2 : Communicating with ActionScript

A variable is basically a container that holds infor-mation. In the illustration shown here, the box onthe left represents the variable that holds thedata. The data is the user names on the right. Thecontainer (the variable) is the same for every user,but every time a different user logs in, that con-tainer is going to hold different data.

Understanding this concept is going to be impor-tant in the next exercise, where you will be creat-ing variables with ActionScript.

Understanding Variables

V I D E O : understandingvariables.movFor more explanation of the concept of variables, check out understandingvariables.mov in the videos folder on the ActionScript HOT CD-ROM.

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 29

Page 17: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

3E X E R C I S E

Setting Variable Data Types

In this exercise, you’ll learn how to create variables and how to assign different data types in ActionScript 3.0.

Choose File > New,and select Flash File(ActionScript 3.0) in theNew Document dialog box.Click OK.

Double-click Layer 1, andrename the layer actions.

New Flash documents alwaysopen with one layer by default.

2

1

30 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 30

Page 18: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Select Frame 1 on the actions layer. Press F9 (Windows) or Opt+F9 (Mac) to open the Actions panel.

To create a variable, the first task you need to perform is to type the word var.

Position your cursor on the firstblank line, and type var followed by aspace. After the space, type userName.

var is a keyword in Flash. Notice that theword turns blue. After the space, youtype the variable name, in this caseuserName. You always have to start withvar, but the variable name can be any-thing you want. However, note variablenames are subject to the same rules assymbol and symbol instance names—nospaces, no special characters, and so on.

Now you will type a value for the variable. In this case, it will be text data, the user’s actual name. Textdata is called a string. Strings in general can be any combination of numbers, letters, spaces, and specialcharacters. Whatever the characters it contains, when you’re defining a string in Flash, you always put thestring between quotation marks.

After userName, type a space, andthen enter the following:

= “Todd”;

You can type your own name if you wanthere. Now comes the important part:setting the variable data type. The vari-able data type does exactly what itsounds like. It defines the type of datathat is going to be held inside the vari-able. Sometimes it will be numbers, and sometimes it will be text, as you see here. You’ll specify the data type for this variable in the next step.

Position your cursor after userName, and type a colon (:). The Code Hint pop-up menu appears again.This time Flash recognizes that the statement is creating a variable and supplies variable data types.6

5

4

3

31Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 31

Page 19: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Type the letters Str. Press Enter(Windows) or Return (Mac) as soon asthe word String is highlighted in theCode Hint pop-up menu.

Make sure to type a capital S in this step,or the code hint won’t work.

Once you hit Enter (Windows) or Return(Mac), your ActionScript statement iscomplete. You can change the variablename and the text string to anything youwant, but var is required. The variabledata type isn’t required to make thisstatement work, but as you’ll see later, typing it prevents Flash from accepting garbage data. If you wereto accidentally type a special character for a Number type variable, you’d want Flash to let you know.

Close the Actions panel, and close the Flash file. You don’t need to save your changes.

In the next exercise, you’ll use something called a trace statement to check a value inside a variable.

8

7

32 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 32

Page 20: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

4E X E R C I S E

Using Trace Statements

One way to make sure your code is syntaxed and running properly is to use trace statements. A tracestatement pops up in the Output panel when you test or publish the movie. It’s kind of like a message to whomever is working on the file, and it stays internal to Flash. The message won’t display, for exam-ple, if you publish the SWF file on the Web. In this exercise, you’ll learn how to set up a trace statement.

Choose File > Open, and open Trace_Statements.fla from the chap_02 folder you copied to your desktop.

Select Frame 1 on the actions layer,and press F9 (Windows) or Opt+F9 (Mac)to open the Actions panel.

This file contains a similar variable state-ment to the one you created in Exercise 3.I’m going to use Sammy for the textstring this time.

Position your cursor after the firstline of code, and hit Enter (Windows) orReturn (Mac) three times until your cur-sor is at the beginning of Line 4. Typethe following:

trace

trace is another keyword, so it will turnblue like var.

Note spaces between lines of code arenot required for the ActionScript to runproperly; they just provide a visual sepa-ration between statements.

3

2

1

33Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 33

Page 21: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Press the spacebar after trace, andtype the following:

(userName);

It’s important to pay attention to the casing of the variable name on Line 1 in this statement. Otherwise, your trace statement won’t return an accurate value.

Press Ctrl+Enter (Windows) orCmd+Return (Mac) to test the movie.

Notice that the Output panel opens when themovie is exported. (It may open in a differentarea of your screen.) The Output panel con-tains the variable value, Sammy. Now this mightnot seem valuable information, but consideryou have a project containing hundreds oreven thousands of lines of code and that codecontains an error. The Output panel gives youno information or a coded error message thatyou can’t understand. That’s when trace state-ments become really valuable. They can helpyou check the code and isolate any problems.

Close the Output panel and the preview window.6

5

4

34 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 34

Page 22: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

In the Actions panel, delete userNamefrom the trace statement, and type “Thiscode is running properly.” (Make sure toinclude the quotation marks.)

The trace statement checks against what-ever portion of the code in which it’sinserted. userName was just the message itreturned after checking the code, not theactual code it was checking. You canchange the string, as you just did, to tailorthe output message to the particularneeds of your project. If you had multipletrace statements, you could tailor the message to the blocks of code in which they were located.

Press Ctrl+Enter (Windows) orCmd+Return (Mac) to test the new message.When you are finished, close the preview win-dow and the Actions and Output panels, andthen close Trace_Statements.fla. You don’tneed to save your changes.

It might still not be entirely clear why or whereor when you use trace statements, but whenyou start to work with more complicated filesin the next few chapters, they will be easier tounderstand. In the next exercise, you’ll learnhow to make comments in your code.

8

7

35Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 35

Page 23: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

5E X E R C I S E

Using Comments

In this exercise, you’ll learn how to insert comments in your code. Comments are notes, usually to your-self or to other coders looking at the file. Comments can explain coding decisions, such as the file organization, or can simply annotate the code. You can also temporarily turn off a block of code using a comment.

Choose Flash File (ActionScript 3.0) in the Create New section of the Welcome screen.

Double-click the name of the first layer, and rename it actions.

Select Frame 1 on the actions layer, and press F9 (Windows) or Opt+F9 (Mac) to open the Actions panel.

First you’ll practice temporarily turning off a line of code.

Position your cursor on the first blankline, and type the following:

trace(“something”);

You may have noticed that whenever youplace a word or phrase in quotationmarks, it turns green in the Actions panel.(If you have modified your ActionScriptpreferences, it may turn a different color.)This is another Flash code assistance fea-ture, called code coloring. Keywords arecolored blue by default, as you saw in aprevious exercise. Strings, such as this textstring, are colored green. Comments, which you’ll add in a moment, are gray. You can turn off code coloring or change the default colors by going to the ActionScript category of the Preferences menu.

4

3

2

1

36 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 36

Page 24: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Press Ctrl+Enter (Windows) orCmd+Return (Mac) to test the movie.

The preview window should be empty whenthe SWF loads, because you didn’t add anycontent to the movie. Because of the tracestatement you added, the Output panelshould open and contain the word something.

Close the preview window and the Output panel.

In the Actions panel, position yourcursor before the trace statement, andtype // (two slashes).

Notice that the entire line of code turnsgray. Two slashes signal to Flash that theline of code is a comment and shouldn’tbe used in the final movie.

Press Ctrl+Enter (Windows) or Cmd+Return (Mac) to test the movie.

Even though the trace statement is still in the code, the Output panel should not open when the movie is exported because you disabled the code.

You can also use comments to leave messages for other coders. Messages can use any combination of characters.

Close the preview window, and return to the Actions panel. After the trace statement, press Enter(Windows) or Return (Mac) twice. Type // to start a new comment.9

8

7

6

5

37Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 37

Page 25: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Type a message of yourchoice, such as Hey fellowcoder, line 1 has been dis-abled until we have morecode to trace.

Both the comment code andthe text will turn gray.

Position your cursor before Line 1, and delete the two slashes. Click and drag to select the entiretrace statement. Press Ctrl+C (Windows) or Cmd+C (Mac) to copy it.

Press Enter (Windows) orReturn (Mac) to go to the nextline. Press Ctrl+V (Windows)or Cmd+V (Mac) to paste thetrace statement.

To disable, or comment out,multiple lines of code such asyou have here, you’ll use amultiline comment.

Position your cursorbefore the first trace state-ment, and press Enter(Windows) or Return (Mac).Press the up arrow key to goto the new first line. Type /*.

Notice that both lines ofcode are now gray.

13

12

11

10

38 ActionScript 3.0 for Adobe Flash CS3 Professional : H•O•T

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 38

Page 26: Communicating with ActionScript - Lynda.comfiles.lynda.com/files/edu-media/EDU_HOT_CHAPTERS/AS3/AS3_Chap_… · Eight handles will appear around the edges of the shape. Position your

Position your cursor onthe next blank line after thesecond trace statement, andtype */ to close the multilinecomment. Press Enter(Windows) or Return (Mac),and on the new line, pressCtrl+V (Windows) or Cmd+V(Mac) to paste the trace state-ment again.

Notice that the trace statement outside the commented block of code stays active.

There’s one more feature to comments I want to show you: the comment tools. The comment tools arelocated above the Script pane and can be used to insert or delete both single-line and multiline com-ments, without having to type the // or */.

Select the third tracestatement, and click the Apply line comment button.

Flash adds the commentmarker before the line, andthe code turns gray. Noticethat Flash inserts the markerson the same line as the code. I prefer to separate them, asyou’ve done in this exercise,to keep the markers and origi-nal code visually separated,but it’s not absolutely necessary. To remove the comment, you simply reselect the code and click the Remove comment button.

Close the Actions panel, and then close the Flash file. You don’t need to save your changes.

Congratulations! You’ve completed the first set of exercises. Now that you know the basics ofActionScript—how to use correct syntax, how to modify properties, how to create variables, and so on—you can move on to building functions. In the next chapter, you’ll learn how to use ActionScript’s built-infunctions, called methods, and how to write custom functions of your own.

16

15

14

39Chapter 2 : Communicating with ActionScript

02_AS3HOT_(14-39).qxd 09/12/2007 10:44 AM Page 39