What Is ActionScript?


If you've been using Flash for a while then you've probably heard of ActionScript. You might not know exactly what ActionScript is or why it's importantjust that it seems to be a hot topic. In this section, you'll learn what ActionScript is used for and will be introduced to some terminology and syntax.

ActionScript is a programming language. It allows you to break your application out of the static mold by enabling your Flash application to react uniquely, based on user input, external data, and even the time of day! It 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 structureall 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. This structure is called syntax.

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.

As an example, let us assume that there is a button that a user will click to submit an order, and the button has an instance name of checkout_btn. Now consider the following script:

  checkout_btn.onRelease = function() {     //set the cost of the mug     var mugCost:Number = 5;     //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, after you become acquainted with some of its elements, you'll understand. Now you'll be introduced to some terms. The preceding script will be explained as you go.

Events

An event is when something happens. There are predefined events that the Flash player gives you access to, such as the act of moving or clicking the mouse. And there are custom events made for special uses, as you'll see later in this book.

Events occur during the playback of a movie and trigger the execution of a particular function. In the preceding sample script, the event that triggers the script is onRelease. This event signifies that when the checkout_btn button instance is released, the script will execute. Every script is triggered by an event, and your movie can react to numerous eventseverything 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 7, "Events, Listeners, and Callbacks."

Actions

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

Here are some examples of actions from the sample script:

   var mugCost:Number = 5;    cashRegister_mc.gotoAndPlay (50);


The first line creates a variable named mugCost, sets its data type as Number (data typing is discussed later), and sets the value of the variable to 5. 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

Operators 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 using the assignment operator, =. This operator assigns the value of what is found to the right of it, to the variable on the left.

  • amountA < amountB asks if amountA is less than amountB.

  • value1 * 500 multiplies value1 times 500.

The operators >, <, >=, <=, ==, !=, ===, are known as comparison operators. They'll be discussed in Lesson 4, "Arrays and Loops."

Keywords

Keywords 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 forth. Attempting to use keywords in your scripts for anything other than their intended purpose will result in errors. Here are some other keywords: 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 data during its execution. Variables are the most common data found in scripts and represent information that has been given a unique name. After 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. The value of a variable is data.

Note

Variable names are case-sensitive: firstname and firstName are not the same.


In our sample script, we created a variable named mugCost and assigned it a value of 5. 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;      //set the local sales tax percentage      var taxPercent:Number = .06;    }


The preceding could be viewed as a sentence that says this: As a result of releasing the button, create two variables called mugCost and taxPercent.

Semicolons

Appearing at the end of most lines of scripts, semicolons are used to separate multiple actions that might 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;     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.NorthCarolina.ElmCity points to a movie clip on the main (_root) Timeline named usa, which contains a movie clip named NorthCarolina, which contains a movie clip named ElmCity.

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 following syntax:

   wheel_mc._rotation = 45;


Notice that 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 this syntax:

   wheel_mc.play()


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

Parentheses

Parentheses 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 is specified between the parentheses.

Quotation Marks

Quotation marks are used to denote textual data in the script, called a string. 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, Kelly (without quotes) signifies the name of a piece of data. On the other hand, "Kelly" signifies the actual word "Kelly."

Comments

Comments 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 is written and still get a clear idea of its underlying logic. They do not affect the outcome of a script.

You can also create multiline comments using the following 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, the following:

   on (release) {    var mugCost:Number = 5;    }


executes the same way as this:

   on (release) {      var mugCost:Number = 5;    }


However, by indenting the second line of 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 blockor chunk of codethat is to be executed at the same time. (The AutoFormat feature of the Actions panel takes care of most of this formatting for you.) You can nest code blocks within other code blocksa concept that will become clearer as you work through the exercises.

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

   var totalCost:Number = mugCost + totalTax ;


executes in the same way as this:

   var totalCost:Number =mugCost+totalTax;


Although 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. Although this syntax is acceptable:

   myObject.propertyName


this syntax 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


You have just gotten your first taste of ActionScript. You have learned a little about what ActionScript is needed and you have been introduced to the various elements that make up ActionScript. Don't worry if the code snippets that you have seen don't make much sensethey aren't supposed to yet! We just talked about what makes up the code, not the logic that goes into creating it. In the coming sections you will learn more about ActionScript and will get a chance to write some yourself.

In this exercise, you will take a look at the ActionScript in an existing Flash file. You'll inspect the elements that make up the code and add a few lines yourself. The goal of this exercise is just to let you poke around in some ActionScript first-hand so that you can relate what you've seen here to an actual simple application.

1.

Open the Balloon1.fla file, found in the Lesson01/Start folder.

The first things that you'll notice when you open this file are the colorful landscape background and the hot air balloon on top of it. When complete, this application will allow you to use the four arrow keys on your keyboard to navigate the balloon through the air. The file already has the necessary ActionScript to allow the left and right arrow keys to control the horizontal movement of the balloon. In the steps to come you will inspect the existing ActionScript and will add a few more lines that let the balloon move vertically as well.

There are four locked layers in this file. The first one is called actions. It is used to store the ActionScript. The second layer, called text, holds a text field that will display text generated by ActionScript. The text field has an instance name of instructions_txt. The next layer, called balloon, contains the balloon image in a movie clip with an instance name of balloon_mc. The bottom layer, called background, simply contains the background image.

2.

Click Frame 1 in the actions layer. Select Window > Actions to open the Actions panel.

The Actions panel will be discussed in great detail in the next section. For now, it's enough to know that it is used to edit ActionScript in a Flash document.

You should see 13 lines of ActionScript in the Actions panel. Some of the lines have text that is completely gray, and some of the lines are multicolored. The grayed-out lines start with //, which means that they are comments. Comments are not considered code; they are usually used to provide a description of the next line (or lines) of ActionScript.

The multicolored lines are lines of ActionScript. You'll notice that ActionScript lines end with a semicolon, and comment lines do not.

3.

Look at the operators in lines 2, 4, 6, 9, and 11.

These lines contain the assignment operator, =, the addition operator, +, and the subtraction operator, -. Operators are used to connect to elements in a script. In line 2, the = operator is used to add text to a text field. In line 9, the + operator is used to increase the x position of the balloon by an amount.

4.

Look at the curly braces, { and }, on lines 6, 8, 10, 12, and 13.

Curly braces are used to group lines of ActionScript. Whenever you have an open curly brace, {, it must eventually be closed by }. The curly brace opened in line 6 is closed on line 13. All lines of ActionScript contained within those curly braces, 712, are grouped together. That group of ActionScript will be executed together when the time comes.

In line 6, we capture an event called the onEnterFrame event. This event occurs once per frame, at the frame rate. This file is set to 24 frames per second (fps) and so the onEnterFrame event will occur 24 times per second. All the code that is grouped within its curly braces will be executed 24 times per second.

The ActionScript on lines 812 checks for one of two conditions. It first checks to see whether the right arrow key is currently pressed. If it is not, then it checks to see if the left arrow key is pressed. If the first condition is met, line 9 is executed. If the second condition is met, line 11 is executed. If neither condition is met, neither line 9 nor line 11 is executed.

There is one other thing to take note of here. Code that is grouped by curly braces is tabbed in one time for every open and closed curly brace in which it sits. Line 9 sits within two sets of curly braces, so it is tabbed in by two tabs.

5.

Notice the dot syntax on nearly every line.

In ActionScript, objects are containers that hold data. They can hold other objects, variables, and functions. Some objects have visual representations, such as movie clips, but most do not. You will learn more about these in the coming sections and lessons.

This is line 2:

   instructions_txt.text = "Use your arrow keys to move the balloon!";


Let's look at this line of code, reading from left to right. The first element is the instance name of the text field found in the text layer, followed by a dot. The dot means that what comes next is inside the text field object. Then there is an = operator followed by a string. The whole line of code sets the text inside of the text field instance equal to the string found to the right of the = operator.

6.

On line 12, click just to the right of } to move the cursor there. Press Enter to add a new blank line to the ActionScript. Type this onto that blank line:

   //move vertically if the UP or DOWN arrow keys are pressed


You just added a comment, which always starts with //. In the next step, you will add ActionScript to enable the balloon to move vertically when the up and down arrow keys are pressed.

7.

At the end of line 13, press Enter to add a new blank line to the ActionScript. Type the following four lines of ActionScript:

   if (Key.isDown(Key.UP)) {      this._y = this._y - speed;    } else if (Key.isDown(Key.DOWN)) {      this._y = this._y + speed;    }


These four lines of ActionScript look very similar to lines 812. The only differences are that they refer to the y position of the balloon instead of the x position, and they check for the up and down arrow keys instead of the left and right arrow keys.

It is not expected that you will fully understand ActionScript at this point in the book. The purpose of this exercise is let you gain a little experience in working with ActionScript.

8.

Generate a test SWF file by selecting Control > Test Movie. Use the four arrow keys to see how the balloon reacts.

The balloon should move left, right, up, and down when those arrow keys are pressed. It's amazing how interactive Flash can be with such few lines of ActionScript!

9.

Close the test movie and save your work as Balloon2.fla.

You should now be familiar with the various ActionScript elements. It will definitely take a little time, practice, and experience to really feel comfortable writing and editing ActionScript. Fortunately, you have this book and the step-by-step exercises to help you through it!

Next, you'll be formally introduced to the Actions panel. And then you'll start writing variables.




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

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