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. EventsAn 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." ActionsActions 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). OperatorsOperators 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:
The operators >, <, >=, <=, ==, !=, ===, are known as comparison operators. They'll be discussed in Lesson 4, "Arrays and Loops." KeywordsKeywords 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. DataA 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 BracesGenerally, 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. SemicolonsAppearing 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 SyntaxDots (.) 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. ParenthesesParentheses 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 MarksQuotation 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." CommentsComments 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/SpacingAlthough 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.
|