Thursday, December 13, 2007

ActionScript Elements

ActionScript is a language that bridges the gap between what you understand and what Flash understands. As such, it allows you to provide both action-oriented instructions (do this) and logic-oriented instructions (analyze this before doing that) in your Flash project. Like all languages, ActionScript contains many different elements, such as words, punctuation, and structure—all of which you must employ properly to get your Flash project to behave the way you want it to. If you don't employ ActionScript correctly, you'll find that interactivity either won't occur or won't work the way you intended. Many of these elements, as well as several other elements such as logical statements and expressions, will be covered in more detail throughout the book.

To begin to understand how ActionScript works, look at this sample script, which contains many of the essential elements that make up a typical script. After the script is a discussion of these elements and their role in the script's execution.

We can assume that this script is attached to a button:

on (release) {

//set the cost of the mug

var mugCost:Number = 5.00;

//set the local sales tax percentage

var taxPercent:Number = .06;

//determine the dollar amount of tax

var totalTax:Number = mugCost * taxPercent;

//determine the total amount of the transaction

var totalCost:Number = mugCost + totalTax;

//display a custom message

myTextBox_txt.text = "The total cost of your transaction is " + totalCost;

//send the cashRegister_mc movie clip instance to frame 50

cashRegister_mc.gotoAndPlay (50);

}


Although at first glance this may look like Latin, once you become acquainted with some of its elements, you'll understand.

NOTE

Other script elements (for example, objects, functions, loops, properties, and methods) are discussed in detail throughout the book.


Events

Events occur during the playback of a movie and trigger the execution of a particular script. In our sample script, the event that triggers the script is on (release). This event signifies that when the button to which this script is attached is released, the script will execute. Every script is triggered by an event, and your movie can react to numerous events—everything from a button being pressed to text changing in a text field to a sound completing its playback, and more. We will discuss events in depth in Lesson 2, "Using Event Handlers."

Actions

These form the heart of your script. An action is usually considered to be any line that instructs Flash to do, set, create, change, load, or delete something.

Here are some examples of actions from the sample script:

var mugCost:Number = 5.00;

cashRegister_mc.gotoAndPlay (50);


The first line creates a variable named mugCost, sets its data type as Number (indicating the variable will hold a numeric value), and sets the value of the variable to 5.00. The second line tells the cashRegister_mc movie clip instance to begin playing at Frame 50 of its timeline.

Generally speaking, most of the lines in a script that are within curly braces ({ } ) are actions. These lines are usually separated by semicolons (we'll discuss punctuation shortly).

Operators

These include a number of symbols (=, <, >, +, –, *, &&, etc.) and are used to connect two elements in a script in various ways. Take a look at these examples:

  • var taxPercent:Number = .06; assigns a numeric value of .06 to the variable named taxPercent

  • amountA <> asks if amountA is less than amountB

  • value1 * 500 multiplies value1 times 500

Keywords

These are words reserved for specific purposes within ActionScript syntax. As such, they cannot be used as variable, function, or label names. For example, the word on is a keyword and can only be used in a script to denote an event that triggers a script, such as on (press), on (rollOver), on (rollOut), and so on. Attempting to use keywords in your scripts for anything other than their intended purpose will result in errors. Other keywords include break, case, class, continue, default, delete, do, dynamic, else, extends, finally, for, function, get, if, implements, import, interface, in, instanceof, new, null, private, public, return, set, static, switch, this, throw, try, typeof, undefined, var, void, while, and with.

Data

A dynamic script almost always creates, uses, or updates various pieces of data during its execution. Variables are the most common pieces of dynamic data found in scripts and represent pieces of data that have been given unique names. Once a variable has been created and assigned a value, that value can be accessed anywhere in the script simply by inserting the variable's name.

NOTE

Variable names are case sensitive: myVariable and MyVariable are not the same.


In our sample script, we created a variable named mugCost and assigned it a value of 5.00. Later in the script, the name of that variable is used to refer to the value it contains.

Curly Braces

Generally, anything between opening and closing curly braces signifies an action or set of actions the script needs to perform when triggered. Think of curly braces as saying, "As a result of this–{ do this} ." For example:

on (release) {

//set the cost of the mug

var mugCost:Number = 5.00;

//set the local sales tax percentage

var taxPercent:Number = .06;

}


Semicolons

Appearing at the end of most lines of scripts, semicolons are used to separate multiple actions that may need to be executed as the result of a single event (similar to the way semicolons are used to separate thoughts in a single sentence). This example denotes six actions, separated by semicolons:

var mugCost:Number = 5.00;

var taxPercent:Number = .06;

var totalTax:Number = mugCost * taxPercent;

var totalCost:Number = mugCost + totalTax;

myTextBox_txt.text = "The total cost of your transaction is " + totalCost;

cashRegister_mc.gotoAndPlay (50);


Dot Syntax

Dots (.) are used within scripts in a couple of ways: One is to denote the target path to a specific timeline. For example, _root.usa.indiana.bloomington points to a movie clip on the main (_root) timeline named usa, which contains a movie clip named indiana, which contains a movie clip named bloomington.

Because ActionScript is an object-oriented language, most interactive tasks are accomplished by changing a characteristic (property) of an object or by telling an object to do something (invoking a method). When changing a property or when invoking a method, dots are used to separate the object's name from the property or method being worked with. For example, movie clips are objects; to set the rotation property of a movie clip instance named wheel_mc, you would use the syntax:

wheel_mc._rotation = 90;


Notice how a dot separates the name of the object from the property being set.

To tell the same movie clip instance to play, invoking the play() method, you would use the syntax:

wheel_mc.play()


Once again, a dot separates the name of the object from the method invoked.

Parentheses

These are used in various ways in ActionScript. For the most part, scripts employ parentheses to set a specific value that an action will use during its execution. Look at the last line of our sample script that tells the cashRegister_mc movie clip instance to go to and play Frame 50:

cashRegister_mc.gotoAndPlay (50);


If the value within parentheses is changed from 50 to 20, the action still performs the same basic task (moving the cashRegister_mc movie clip instance to a specified frame number); it just does so according to the new value. Parentheses are a way of telling an action to work based on what's specified between the parentheses.

Quotation Marks

These are used to denote textual data in the script. Because text is used in the actual creation of the script, quotation marks provide the only means for a script to distinguish between instructions (pieces of data) and actual words. For example, Derek (without quotes) signifies the name of a piece of data. On the other hand, "Derek" signifies the actual word "Derek."

Comments

These are lines in the script preceded by two forward slashes (//). When executing a script, Flash ignores lines containing comments. They indicate descriptive notes about what the script is doing at this point in its execution. Comments enable you to review a script months after it was written and still get a clear idea of its underlying logic.

You can also create multi-line comments using the syntax:

/* everything between

here is considered

a comment */


Indenting/Spacing

Although not absolutely necessary, it's a good idea to indent and space the syntax in your code. For example:

on (release) {

var mugCost:Number = 5.00;

}


will execute the same as:

on (release) {

var mugCost:Number = 5.00;

}


However, by indenting code, you make it easier to read. A good rule is to indent anything within curly braces to indicate that the code within those braces represents a code block, or chunk of code, that is to be executed at the same time. (The AutoFormat feature of the Actions panel takes care of most of this for you.) You can nest code blocks within other code blocks—a concept that will become clearer as you work through the exercises.

For the most part, white space is ignored within a script. For example:

var totalCost:Number = mugCost + totalTax ;


will execute in the same way as:

var totalCost:Number =mugCost+totalTax;


While some programmers feel that extra white space makes their code easier to read, others believe it slows them down to insert spaces. For the most part, the choice is yours. There are a couple of exceptions: variable names cannot contain spaces; nor can you put a space between an object name and an associated property or method. While this syntax is acceptable:

myObject.propertyName


this is not:

myObject. propertyName


In addition, there must be a space between the var keyword used when creating a variable, and the actual name of the variable. This is correct:

var variableName


but this is not:

varvariableName

Using the Actions Panel/ActionScript Editor

Obviously, the premise of this book requires you to concentrate on writing scripts. It's a good idea to get familiar with the tools you'll use in Flash to do so. In this, your first exercise, you'll learn some of the basics of creating scripts with the ActionScript editor.

NOTE

The purpose of this book is to teach ActionScript, not so much how to use the Flash interface. This discussion will be concise, providing enough information to help you progress through the book. For a more extensive look at the many features of the Actions panel, pick up the Macromedia Flash Visual QuickStart Guide.


  1. With Flash open, choose File > New and choose Flash Document from the list of choices. Press OK.

    This step creates a new Flash document. It's usually a good idea to give your document a name and save it, so we'll do that next.

  2. From the File menu, choose Save As. In the dialog box that appears, navigate to any folder on your hard drive where you would like to save this file (it's not important where, really), name it myFirstFile.fla, and press the Save button.

    After you press Save, the tab at the top of the document window will reflect the name of your new file.

  3. Open the Actions panel by choosing Window > Development Panels > Actions.

    Let's look at the various sections of the Actions panel.


    The Script pane is where you add ActionScript. You type into this window just as you would a word processor. The script that appears in this window changes, depending on the currently selected element in the Flash authoring environment. For example, selecting a keyframe on Frame 10 allows you to place a script on that frame if one doesn't already exist; if that frame already contains a script, it will be displayed for editing.

    The Actions toolbox contains a categorical list of ActionScript elements. Double-clicking an icon (a book with an arrow) opens or closes a category in the list. The toolbox is designed to provide a quick way of adding script elements to your scripts for further configuration. You can add script elements to the Script pane by double-clicking the element's name in the toolbox window, or by clicking and dragging it to the Script pane.

    The Script Navigator displays a hierarchical list of elements (frames, buttons, movie clip instances) in your projects that contain scripts. Clicking an element will display the script attached to it in the Script pane, allowing you to navigate quickly through the scripts in your project for editing purposes. Only elements with scripts attached to them appear in the Script Navigator.

    The Script pane toolbar appears above the Script pane and provides a series of buttons and commands, enabling you to add to or edit the current script in the Script pane in various ways.

    In the next steps, we'll explore the capabilities and functionalities of the ActionScript editor. Let's look first at code hinting.

  4. In the Script pane, type:

    myMovieClip_mc.


    NOTE

    Let's assume this is the name of a movie clip instance we've placed in our movie.

    Immediately after you type the dot (.), a drop-down menu provides a list of actions applicable to movie clip instances.


    Why did the editor provide a list of commands for movie clip instances? It's because of the name we chose for our movie clip instance. Notice that we added _mc to the movie clip instance's name. This suffix enables the editor to automatically identify myMovieClip_mc as a movie clip instance and provide a drop-down list of appropriate commands when you type that name in the Script pane.

    Common suffixes for visual movie elements include _btn for buttons and _txt for text fields. We will be using these suffixes for visual elements throughout this book.

    Other, nonvisual elements, such as Sound and Date objects, have suffixes as well, but instead of using suffixes for nonvisual elements, we'll instead be utilizing a new functionality in Flash MX 2004, which we'll demonstrate next.

    NOTE

    For a complete list of suffixes, consult the ActionScript Dictionary.

  5. Select the current script and delete it. In its place, type:

    var mySound:Sound = new Sound();


    This line of script creates a new Sound object named mySound. Creating a Sound object using this syntax identifies mySound as a Sound object to the ActionScript editor. As a result, referencing this object by its name later in the script will cause a drop-down menu of appropriate Sound object–related commands to appear automatically. Let's test it.

  6. Press Enter/Return to go to the next line in the Script pane, and type:

    mySound.


    Once again, immediately after typing the dot, you see a drop-down menu with a list of actions applicable to Sound objects.

    You can create a new Sound object using this syntax:

    mySound = new Sound();


    but this syntax will not activate the functionality of code hinting when you script that object, as the syntax in Step 5 does.

    To help you grasp this concept, let's look at a couple more examples.

    This code activates Color object–related code hinting for the myColor Color object:

    var myColor:Color = new Color();


    This code does not:

    myColor = new Color();


    This code activates Date object–related code hinting for the myDate Date object:

    var myDate:Date = new Date();


    This code does not:

    myDate = new Date();


    NOTE

    To clarify, in this book we will be using suffixes only when naming visual elements such as movie clip instances, text fields, and buttons. This is because visual elements are not created in the same manner as the description in this step. Using suffixes in their names is the only way to activate code hinting when referencing them in the ActionScript editor.

    Let's look next at another type of code hint available in the ActionScript editor.

  7. Select the current script and delete it. Type in its place:

    getURL(
  8. Planning a Project

    When creating a project that contains a generous amount of ActionScript, it's wise to do some planning up front. Dealing with problems in the idea stage makes a lot more sense than dealing with them in the development stage, where they often require more time and cause frustration before they are fixed. We guarantee you'll save time in the long run.

    Many issues must be addressed before you even open Flash and start scripting. A good way to go about this is to ask yourself a series of questions.

    What do you want to occur?

    This is the most important question in the script planning process. Be as clear, informative, and visual as possible in your answer, but avoid going into too much detail.

    For the project we discuss in this lesson, we want to create a scene that acts as a front end for paying an electric bill. We want the amount of the bill to be loaded into the movie from an external source, a text file. We want to allow the user to enter an amount to pay into a text box. When a button is pressed, the amount the user paid will be compared to the amount he or she owed, and a visual and textual representation (a custom message) of the result—overpaid, underpaid, or paid in full—will be presented. When the user releases that button, we want the visual and textual elements in the scene to return to their original state. The script that accomplishes this will be the main script in the project.

    What pieces of data do you need to track?

    In other words, what numbers or values in the application are integral to its function? In our case, that data is the amount of the electric bill. We will also need to keep track of the difference between what the user owes and what he or she has paid, so that we can display that value in custom messages.

    What needs to happen in the movie prior to a script being triggered?

    In our project, the amount of the electric bill must be established in the movie before anything else can happen. Because the primary goal of our project is to compare the amount of the electric bill with the amount the user chooses to pay, if the amount of the electric bill isn't established when the movie first plays, there will be nothing to compare when the script is executed. Creating and setting data prior to a script's being executed, or when a movie first plays, is known as initializing the data—a common practice in scripting and something that's usually transparent to the user.

    At this point, you need to start thinking about how the data—the amount of the electric bill—will get into the movie. You can place it within the movie when you author it, or you can have it loaded from an external source (for example, a server or text file) when the movie plays. For our project, we opt for the latter: We use a simple script to load a text file containing the amount of the electric bill into the movie. The text file loaded into the movie to provide data is known as a data source.

    What event will trigger the main script?

    In our case, the answer is obvious: a button press. However, all kinds of events can trigger a script in Flash, so it's important to give some thought to this question. Does something need to happen when a user moves, presses, or releases the mouse, or when he or she presses a key on the keyboard? How about when a movie clip first appears in the scene? Or does the event need to happen continually (the whole time the movie is playing)? We'll discuss such events in detail in the next lesson.

    Are there decisions to be made when the main script is triggered?

    When the main script in our movie is triggered, the amount the user enters to pay needs to be compared with the amount he or she owes to determine whether the payment amount is too much, too little, or right on target. The answers to these questions will determine the custom message to display as well as what other visual elements are visible on the screen.

    What elements make up the scene? How do they function?

    Our scene will be made up of a number of elements, some of which we need to name so that ActionScript can use, control, and/or interact with them. To trigger the script, our scene will need a button, which will look like a pay button found on many sites.

    We also need a dynamic text field to display the amount of the bill; we'll name this text field owed_txt. In addition, we need an input text field where the user can enter the amount he or she wishes to pay; we'll name this text field paid_txt. We also need a dynamic text field to display the custom message generated by the script; we'll name this text field message_txt. Finally, we'll add a graphic of a rubber stamp in the form of a movie clip instance with four visual states. Initially, the stamp will not be visible. If the user has not paid enough, a stamp will appear, indicating underpayment. A stamp showing payment in full will appear if the user pays the exact amount, and another showing overpayment if the user overpays. This rubber-stamp movie clip instance will be named stamp_mc.

    What will your scene look like?

    Use whatever means you want—an illustration program or a pencil and napkin—to create a rough graphical representation of your scene (both its appearance and the action that will take place), as shown in the diagram below. Include all the information you've gathered at this point. This important part of the planning process is often called storyboarding.

    As you grow more proficient at ActionScript and develop additional projects, you'll soon be able to ask (and answer) the previous planning questions intuitively. However, no matter what your skill level, storyboarding remains an essential part of the planning process.




    graphics/01inf04.gif

    Once you type the opening parenthesis, a code hint ToolTip will appear. This functionality becomes active when you type the code for an action that has definable parameters, such as the getURL() action. The currently definable parameter will appear in bold text within the ToolTip. As you enter various parameter data (separated by commas), the ToolTip will be updated to display the currently definable parameter in bold text. The ToolTip will disappear once you type the closing parenthesis for the action.

    You can manually display code hints at any time by placing the insertion point (cursor) at a location where code hints normally appear automatically (such as just after the opening parenthesis of an action), then pressing the Code Hint button on the Script pane toolbar.

    graphics/01inf05.gif

    Other buttons on the toolbar allow you to find words in your scripts, replace words in your scripts (a great feature if you change the name of something), insert target paths, check scripts (without having to spend extra time to actually export the entire movie), and autoformat your scripts (allowing the editor to handle the job of formatting your scripts in an easy-to-read manner).

    The last aspect of the ActionScript editor that we'll discuss here is its ability to create .as files.

  9. From the File menu, choose New and select ActionScript File from the list of choices. Press OK.

    This step creates a new ActionScript file, ready for editing in the ActionScript editor.

    The ActionScript editor looks very similar to how it looked in the previous steps. The most noticeable difference is the fact that while the interface elements of the editor are active, the rest of Flash's interface is dimmed out. Flash enters this "limited" mode when you edit .as files. The reason is that in this mode its sole purpose is to enable you to create and edit .as files. Drawing tools and other panel functionalities have no meaning in this context.

    TIP

    You can rid the interface completely of dimmed-out interface elements by pressing F4. Pressing F4 again brings them back.

    Another noticeable change is the disappearance of the Script Navigator. Once again, because this mode is meant for editing .as files, the concept of navigating various scripts in a project has no meaning, and the Script Navigator is nonexistent in this mode. Other than these differences, the ActionScript editor works in the same manner as previously discussed in this exercise.

    When you create .as files (as you'll be doing later in the book), you save them by choosing File > Save and providing a name.

    NOTE

    In most cases in this book, unless otherwise stated, .as files (once we begin creating them) should be saved in the same directory as your main .fla files.

    One last thing to note about the Flash authoring environment is that two tabs now appear at the top of the document window. One tab represents the Flash document we created in Step 1, and the other represents the open ActionScript file we just created. Clicking on these tabs allows you to switch easily between authoring the Flash document and the ActionScript file. Flash automatically switches editing modes when you do.

    graphics/01inf06.gif

    This completes the exercise. Next, you start creating your first application.

No comments: