Thursday, December 13, 2007

Introducing ActionScript

Introducing ActionScript

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.

We'll plan, create, and test a highly interactive electric-bill payment system.

In this lesson, we'll introduce previous ActionScripters to version 2.0 of the language. xFor 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.

WHAT YOU WILL LEARN

In this lesson, you will:

  • Learn about ActionScript 2.0 and how it differs from ActionScript 1.0

  • Discover the benefits of learning ActionScript

  • Learn to navigate and use the ActionScript editor

  • Learn about script elements

  • Plan a project

  • Write your first script

  • Test your script

  • Debug your script

APPROXIMATE TIME

This lesson takes approximately one and one half hours to complete.

LESSON FILES

Starting File:

Lesson01/Assets/electricbill1.fla

Completed Projects:

electricbill2.fla

electricbill3.fla

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.

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;

}

}

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




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.

No comments: