Introducing ActionScript
Note: The following article is an excerpt from Macromedia Flash MX 2004 ActionScript: Training from the Source by Derek Franklin and Jobe Makar.
Introductions form the start of any great relationship. Get ready, then, to be introduced to your new best friend: ActionScript! We believe you'll find ActionScript a satisfying companion—especially as you delve deeper into the relationship. Although you may not necessarily think of scripting as a creative endeavor, a working knowledge of ActionScript can spark all kinds of ideas—ones that will enable you to create dynamic content that can interact with your users on myriad levels. Best of all, you'll get the satisfaction of watching your ideas grow into working models that fulfill your projects' objectives.
In this lesson, we'll introduce previous ActionScripters to version 2.0 of the language. For new users, we'll show you some compelling reasons for learning ActionScript, as well as what makes it tick. And if you're feeling a little shy, sometimes the best thing to do is jump right in—which is exactly what you'll do here as you create and test a complete interactive project before lesson's end.
Requirements
Macromedia Flash MX 2004
Download Lesson 1
astfts_lesson1.pdf
(325 KB)
Buy the Book
Macromedia
Flash MX 2004 ActionScript: Training from the Source
ActionScript Matures to Version 2.0
If you've been involved with Flash for any length of time, you've seen it evolve from a simple multimedia tool used for creating animated web graphics and interactive buttons into a multimedia powerhouse that can play external MP3 files, load graphics, play video, talk to a database, and more.
The passionate and innovative community of Flash developers worldwide drives this evolution, to a large degree. By constantly pushing Flash development to new heights, they make us aware not only of the possibilities, but also of the limitations of what can be done.
Fortunately for us, with each new version of Flash, Macromedia strives hard to address these limitations, providing developers with the tools that enable us to do more cool stuff, in the easiest, most efficient manner.
Since its introduction in Flash 5, ActionScript has enabled Flash-based content to soar to new heights, yet there have been obstacles and limitations discovered along the way.
The execution of ActionScript in the Flash 5 player tended to be slow. Tasks that required milliseconds in other scripting/programming languages took seconds with ActionScript. Ask game programmers and they'll tell you that the speed of processing seemed like a lifetime, and it really limited the kind of interactivity that could be used.
In addition to slow processing speeds, ActionScript in Flash 5, while powerful, wasn't very flexible. There wasn't an easy way of implementing object-oriented programming techniques, which enable the creation of more complex and manageable Flash applications.
ActionScript in Flash MX, though not officially dubbed anything more than ActionScript 1.0 with some enhancements, probably could have rightfully been called ActionScript 1.5. It addressed a number of the processing speed issues that plagued Flash 5 ActionScript. In addition, the capabilities of ActionScript in Flash MX were enhanced in ways that enabled the implementation of common object-oriented programming techniques, including the creation of custom object classes and inheritance. While this was definitely a huge step in the right direction, there was still room for improvement.
With Flash MX 2004, Macromedia has introduced ActionScript 2.0. With it come some new capabilities and, more importantly, some new syntax and a new way of structuring and working with your code.
As we discuss in the next section, the changes are somewhat subtle, but they move ActionScript into the realm of a professional-grade programming language. And with what people are demanding from their Flash applications these days, this is definitely a move in the right direction.
Note: If you're just learning ActionScript, feel free to skip this section (which probably won't make sense) and move on to the next.
Differences Between ActionScript 1.0 and 2.0
If you're familiar with ActionScript 1.0, you'll find that ActionScript 2.0 is similar, yet it has several subtle but important differences. In this section, we examine some of them so that you can take your hard-earned knowledge of ActionScript 1 and put it to use with ActionScript 2.0.
Before we look at these differences, let us first tell you up front that if you want to stick with what you know (programming in ActionScript 1.0), then by all means, do so. ActionScript 1.0 syntax still works in Flash MX 2004. But while this may be the case, and you do have a choice, we recommend you take the time to learn ActionScript 2.0, for a number of reasons.
First, there may come a time when a version of Flash is released that no longer supports ActionScript 1.0. Time spent learning version 2.0 now will be time you might have to spend down the road anyway. And while we can't guarantee it, don't expect ActionScript to jump to version 3.0 any time soon (if ever), because version 2.0 is now built around professional programming language concepts that have stood the test of time. As a matter of fact, outside of a few syntactical differences, writing ActionScript 2.0 code is not much different from writing Java code.
That's right; if you take the time to learn ActionScript 2.0, you'll be able to quickly transition your knowledge to the Java universe, where industrial-strength, cross-platform applications are standard. Consider learning ActionScript: it's a two-for-one deal!
Second, by its very nature and requirements, ActionScript 2.0 will force you to become a more efficient, organized, and better coder. As you will soon see, ActionScript 2.0 has some very strict requirements about how things are done. It's a lot less forgiving than ActionScript 1.0. This may seem like a bad thing, but it actually prevents you from being too sloppy with your scripts, which can make finding bugs a pain, and which can make updating a project months later an arduous task.
Finally, if speed is important to you, you'll be happy to know that ActionScript 2.0 has been shown to be three to seven times faster than ActionScript 1.0. This speed increase will promote the development of even more robust Flash applications.
Let's next look at some of the main differences you'll find between ActionScript 1.0 and ActionScript 2.0.
Case Sensitivity
In ActionScript 1.0, these variable names referenced the same variable:
myVariable MyVariable
In ActionScript 2.0, however, they would be considered two separate variables due to the case difference in their spelling; the first variable begins with a lowercase character, while the second an uppercase character. In fact, all of the following are considered different elements in ActionScript 2.0:
myName MyName MYNAME myname myNAME
This case sensitivity rule applies to all elements in ActionScript 2.0, including instance names, keywords, method names, and so on. Thus, while this syntax will stop all sounds from playing:
stopAllSounds();
this will cause an error:
stopallsounds();
Tip: One easy way of testing for case errors is to press the Check Syntax button on the Actions panel. Errors resulting from case mismatches will appear in the output window.
Strict Data Typing
Variables are used to contain data. This data comes in many forms, including strings of text, numbers, true/false values, references to objects such as movie clip instances, and so on. In ActionScript 1.0, when creating a variable, Flash would automatically assign a data type to it. In this example, Flash understood that the value on the right was of the Number data type:
myVariable = 36;
While Flash will still automatically recognize this variable as holding a Number data type, ActionScript 2.0 introduces what is known as strict data typing, which gives you more control over setting a variable's data type. Here's how it works.
When creating a variable with ActionScript 2.0, you use this syntax not only to create the variable, but also to assign its data type at the same time:
var myVariable:Number = 36;
As you can see, this syntax is not that different from what you're used to using in ActionScript 1.0. The difference is the addition of the var keyword, and the explicit declaration that this variable will hold a number, as indicated by the :Number syntax.
A variable that will hold a string looks like this:
var myOtherVariable:String = "Hello";
In addition to assigning data types to regular variables, strict data typing is used in the creation of object instances:
var myArray:Array = new Array();
and function definitions:
function myFunction (name:String, age:Number)
Note: Both of these types of strict data typing will be explained in greater depth later in the book.
How can all those extra keystrokes be an enhancement? Well, there are several ways.
If you're familiar with the Actions panel's ability to provide code hints (which we will discuss shortly), you'll be happy to know that strict data typing activates code hinting for named elements. For example, if you create an Array object using the syntax:
var myArray:Array = new Array();
the Actions panel will recognize from that point forward that any reference to myArray is a reference to an Array object, and it will automatically provide Array object code hints whenever you script that object. In some cases, this new ability eliminates the need for a suffix (_array, _xml, and _color, for example), which was one of the ways that Flash MX enabled code hinting for an object. While the new syntax requires a few more keystrokes, you'll save a few because you no longer have to add suffixes to elements' names, so consider it a decent trade-off.
Note: You'll notice we said that in some cases the new ability eliminates the need for suffixes. Visual elements (movie clip instances, buttons, text fields, and components, for example) are not created and named in the same manner as data elements. For this reason, suffixes for these elements' names (such as _mc, _btn, and _txt) are still useful. For this book, we will generally use suffixes only for visual elements.
Code hinting isn't the only benefit to strict data typing. By indicating the type of data a variable will hold, you save the Flash player a whole lot of time trying to figure it out on its own. When the Flash player is running your application, Flash needs to keep track of the type of data each variable contains. If you use strict data typing, you make this process a lot easier and less processor-intensive for the Flash player. As a result, your scripts will execute much faster. If you want to increase the speed of your applications, use strict data typing.
Finally, strict data typing can be a very simple way of helping you uncover bugs in your code. Here's an example:
var favoriteBand:String;
This line of script creates a variable named favoriteBand, which has been strictly typed to hold a String.
Later in your script you assign this variable a value or give it a new one using the syntax:
favoriteBand = "The Beatles";
However, if somewhere in your script you use something like this syntax:
favoriteBand = 46;
the Output panel will open and display a "Type mismatch" error when you attempt to export (compile) your movie. This is an error indicating that you've attempted to assign an incorrect value type to a variable. In our example, we've attempted to assign a numeric value (Number data type) to a variable that has been set up to hold a string value.
This functionality can help prevent a number of bugs that can result from simple mistakes you might make when assigning values to variables.
Class Structure
Perhaps the biggest change in ActionScript 2.0 is the way that object-oriented programming is implemented. For example, with ActionScript 1.0, a custom class of objects was defined this way:
_global.Person = function (name, age){
this.name = name;
this.age = age;
}
In ActionScript 2.0, the same class is created using this syntax:
class Person {
var name:String;
var age:Number;
function Person (name:String, age:Number){
this.name = name;
this.age = age;
}
}
Notice the use of the new class keyword. This syntax is very similar to the syntax for creating classes of objects in Java. As you learn more about this syntax (which we won't discuss in detail at this point), you'll quickly see its benefits over ActionScript 1.0.
Another subtle difference in creating custom classes of objects between ActionScript 1.0 and 2.0 is that the script that contains the class definition must exist in its own external .as file. This means that the script for defining the Person class would need to be saved as an external .as file (which is nothing more than a text file with a .as file extension) named Person.as. This is different from ActionScript 1.0, which allows you to place the code for a class definition on Frame 1 of a movie clip's timeline. This is no longer possible when creating content for the Flash 7 player. Class definitions must exist in an external .as file. We'll discuss this functionality in Lesson 7, "Creating Custom Classes." For now, be aware of the difference.
Note: You can still place scripts on frames, buttons, etc., but class definitions must exist in their own .as files.
To make the creation of .as files as easy as possible, Flash MX 2004 now provides a stand-alone ActionScript editor, which is separate from the Actions panel, and which is used for nothing more than the creation and saving of .as files. Later in this lesson, we'll look at both the Actions panel and the stand-alone ActionScript editor.
There are other differences between ActionScript 1.0 and ActionScript 2.0, but this brief overview should provide you with enough insight to get started if you've worked with ActionScript 1.0.
Similarities Between ActionScript 1.0 and 2.0
Okay, up to this point we've only talked about everything that's different between the two versions of ActionScript. But what about them is the same? What hard-earned knowledge of ActionScript 1.0 that you currently have is still applicable to ActionScript 2.0? Fortunately, plenty!
You still control movie clips with this syntax:
myMovieClip_mc.gotoAndPlay(15);
You still create conditional statements the same way:
if (myNumber1 + myNumber2 == 20 && enabled != true){
//actions;
}
or looping statements this way:
for (i = 0; i <= myVariable; ++i){
//actions;
}
Expressions are still created the same way:
myVariable = (myNumber1 / 2) + (myNumber2 + 15);
And scripts can still be assigned to button and movie clip instances using the on() and onClipEvent() event handlers.
Why Learn ActionScript?
Today, if you're a Flash developer, one thing is certain: animation skills, no matter how phenomenal, are no longer enough. A firm grasp of ActionScript is essential because without it, only the most elementary interactivity is possible. By acquiring an in-depth knowledge of ActionScript, you can:
- Provide a personalized user experience
- Achieve greater control over movie clips and their properties
- Animate elements in your movie programmatically—that is, without using the timeline
- Get data in and out of Flash to create forms, chat programs, and more
- Create dynamic projects that respond to the passage of time or the current date
- Dynamically control sound volume and panning
- Do much more
Add to these benefits the fact that viewing and interacting with Flash content can be more than just a web experience. Flash can create self-running applications or mini-programs that operate independently of the browser—a capability more people are putting to use to create games, learning applications, and more. If you want to do this, too, you need at least an intermediate knowledge of ActionScript.
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 namedtaxPercentamountA < amountBasks if amountA is less than amountBvalue1 * 500multiplies 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
About the authors
Derek Franklin is director of derekfranklin.com, a resource dedicated to helping developers worldwide get the most out of Flash. He's been involved in web design since 1995, having served as a multimedia director for a nationally recognized media company. He is the author of Flash 5! Creative web Animation and coauthor of Macromedia Flash MX: Creating Dynamic Applications by Macromedia Press.
Jobe Makar, who specializes in games and applications programming, is co-founder of Electrotank, Inc., where he is Senior Game Developer. He is a contributing author to Macromedia Flash MX: Creating Dynamic Applications.
Macromedia Flash MX 2004 ActionScript: Training from the Source
Sure, you can use Flash MX 2004 without being a master programmer, but as any Flash developer worth his or her salt will tell you, you're not tapping all of its power unless you're taking advantage of its scripting language—ActionScript 2.0—which offers a more robust programming model and better object-oriented programming support than ever before. Here to take the fear factor out of learning it are Flash veterans and best-selling authors Derek Franklin and Jobe Makar, who demonstrate that scripting is an instinctual process you already know by translating real-life activities into ActionScript scripts. In these pages, you'll find methodologies and techniques for building over 40 real-life Flash ActionScript projects, including sample games, applications, web sites, and more. New in this edition are coverage of ActionScript 2.0, web services, Components, Printing, Video, and more. On the companion CD, you'll find all the project files and images you need to complete each project.