AS2 Tutorial 1: Linking a movie-clip to a class (or "Look, ma, no code in the FLA!")

FLAs are Evil

I don't have code in my FLAs. Some people don't like milk in their coffee, I don't like code in my FLAs and I'll tell you why: the FLA is one of the major risk factors in a Flash project.

Top three reasons why I don't like FLAs:

1. They're binary, you can't diff them.

2. Two people can't work on the same FLA at the same time (even when using source control systems like Subversion or CVS that allow this workflow on text files.)

3. They can get corrupted.

That and I hate pronouncing "FLA" properly (I call it an "F-L-A" not "flah!") So, I wouldn't mind if we all woke up tomorrow and realized that FLAs had gone away for good. (Incidentally, you can make them go away and I've heard that it only takes about £12,000 for a Flex license to make it happen!)

So, because they can get corrupted and because they limit your workflow, I consider FLAs as a major risk factor in Flash development. When you start putting code in them, you just make things worse. Have you ever had to hunt through movie clip after nested movie clip for the bit of code that does what you're looking for? Anyone who has can share with you that it's not a pleasant experience. Code in the FLA, especially on frames and in movie clips makes for a tangled, unmaintainable mess.

But, Aral, I #include all my code!

So, if code in the FLA is such a no-no, what is a good Flash developer to do? Well, until Flash MX 2004, your options were limited. The best-practices method for architecting Flash sites and applications was to use external .as files for code and use the #include precompiler directive to have them loaded into Flash at compile-time. This was good, but it still meant that you needed at least one line of code in your FLA, the #include directive. Being a perfectionist, of course, your goal should be zero lines of code in the FLA and that is exactly what AS2 and Flash MX 2004 let you do by linking classes to movie clips.

Besides being anal about code in the FLA, there is another reason for linking classes to movie clips: It provides a more object-oriented approach to Flash development, allows for better encapsulation and makes it possible to implement a forms-based development process in Flash. These are all things that will be covered in later installments to this series.

Exercise 1: Linking a MovieClip to a Class

In this exercise, you're going to jump right in and get your feet wet animating a movie clip using a linked ActionScript 2 class and zero lines of code in the FLA.

Download the exercise files (~15kb).

Part 1 – Setting up your FLA

1. Start a new Flash Document in Flash MX 2004 (File->New

->Flash Document; Ctrl-N)

2. Save the document in the folder you unzipped the exercise files to as balloon_work.fla

3. Set your document dimensions to 430px by 75px in the Document Properties dialog box (Modify->Document

; Ctrl-J)

4. Import the bitmap called balloon.jpg from the exercise files on to your Stage. (File->Import->Import to Stage

; Ctrl-R). Flash will automatically create a keyframe and place the imported bitmap into it.

5. Name the layer that you imported the bitmap on to "Balloon". (Double-click the layer name in the Timeline to change it.) Your screen should now resemble the screenshot below.

6. In order to do anything meaningful with this bitmap (like animate it across the screen), you need to make it into a movie clip symbol. To do this, select the balloon bitmap on Stage by clicking on it and select Modify->Convert to Symbol from the menu (or press F8).This will bring up the Convert to Symbol dialog box, shown below. Enter "Balloon" as the symbol's name and make sure that "Movie clip" is selected as the symbol's behavior. Click "OK" to close the dialog box.

7. Click your newly created movie clip to select it and, using the Property Inspector, place it at the top-left corner of the stage. (Set its X and Y properties to zero.)

8. Open your Library (Ctrl-L) and take a look at what's in there. You should see a bitmap called Balloon and a movie clip called Balloon.

To link the Balloon movie clip to a class you need to right-click it and select "Linkage

" from the context-sensitive menu. This will bring up the Linkage Properties dialog box as shown below.

9. Click the "Export for ActionScript" checkbox. This will activate the "Identifier" and "AS 2.0 Class" textboxes.

10. In the Identifier box, enter "Balloon". This is the name you would use to refer to this movie clip if you wanted to attach it on to the Stage programmatically using the attachMovie() function in ActionScript.

11. Now for the part you've been waiting for: You're going to link this movie clip symbol with a class. This mysterious entity we call a Class is going to provide the brains of the movie clip. It is going to tell it how to behave and what to do.

Your brain is both a part of you and yet, at the same time, a self-contained organ of its own. This is the same for a class, which, in its simplest sense, is a self-contained body of code that has a name and is kept in an external text file that has the same name as the class.

When you link a class to a movie clip, the two become as one. In the class, you can refer to the movie clip as "this" and use movie clip properties like _x, _y and _alpha as well as movie clip methods (functions) like gotoAndStop() and play(). In fact, in ActionScript 2, you don't even have to use this to refer to the properties and methods of a class from within itself, so this._x = 100; becomes equivalent to _x = 100. You will see the latter form used in the rest of the exercise.

Enough talk, let's do it: Tell the movie clip that it needs to link to the class called Balloon by entering "Balloon" in the "AS 2.0 Class" text box.

When you're done, the dialog box should look exactly like the one shown below.

12. Click OK to accept your changes and save the FLA.

Let's recap what we've done: We've created a new Flash document and imported a bitmap into it. We then converted the bitmap to a movie clip using the Convert to Symbol dialog box. Then, we used the Linkage Settings dialog box to link the Balloon movie clip to the Balloon class.

Test your Flash movie using Control->Test Movie (Ctrl+Enter). You should see the error message below in your Output Window:

**Error** Symbol=Balloon, layer=Baloon bitmap, frame=1:Line 1: The class 'Balloon' could not be loaded.

Total ActionScript Errors: 1 Reported Errors: 1

The error tells you that Flash tried to link the class Balloon to the Balloon movie clip symbol but could not find the class. This is not very surprising since you haven't written it yet! In Part 2, you will learn how to make this error go away and even make the Balloon animate across the stage!

Part 2 – Writing the class

Now that you have a movie clip in your FLA that is linked to a class, you need to actually write the class.

1. Using Flash (File->New->ActionScript File) or your favorite text editor, create a new, empty text file.

2. Save the file in the same folder as your FLA and call it Balloon.as.

Notice two things:

One: You gave the file name the same name as the class. This is an ActionScript 2 requirement. There can only be one class per file and the file must be named with the name of the class. (Print this out, frame it and hang it on your wall – it's ActionScript 2 Rule #1.)

Two:You saved the file in the same folder as the FLA. This is very important. You told Flash to link the movie clip symbol to the class "Balloon". To Flash, this means "the class Balloon that is either in the classpath or in the same folder as this FLA." You will learn about the classpath later and also see how you can place your class files in different locations.

3. Now, you're going to create the simplest class possible so that your FLA compiles without giving you errors.

Enter the following code and save your file.

ActionScript:
  1. class Balloon
  2. {
  3. // nothing
  4. }

4. Return to Flash and test your FLA again. It should now compile and run without errors. It doesn't appear to be doing anything particularly interesting however, is it? You can change that by adding some code to the Balloon class.

5. To start, you need to somehow tell Flash that you would like the Balloon class to use the methods (functions) and properties of the MovieClip class. For example, you want to be able to move the balloon by changing its _x (horizontal coordinate) property.

You do this using the extends keyword. Modify your code as shown below and test the movie again:

ActionScript:
  1. class Balloon extends MovieClip
  2. {
  3. // nothing
  4. }

Again, nothing happens but there is a big difference under the hood. Your Balloon class now contains all the properties and methods of the MovieClip class. In object-oriented parlance we call this "inheritance." So, we would say "the Balloon class has inherited the methods and properties of the MovieClip class."

Now that the Balloon class has some methods and properties, you can use one to make it do something. To start with, let's keep it simple and simply move the balloon 100 pixels to the right. You can do this by setting its _x property (which it inherited from the MovieClip class) to 100.

Modify the code in the Balloon class so it matches the listing below:

ActionScript:
  1. class Balloon extends MovieClip
  2. {
  3. function onLoad ()
  4. {
  5. _x = 100;
  6. }
  7. }

Test your movie and you should see that the balloon jumps to its new location immediately after loading.

The method (function) we created is a special movie clip method called onLoad(). It is known as an "event handler." This is because it gets called to handle an event. The event, in this case, is the "Load" event – which occurs when a movie clip finishes loading in and is ready to be displayed on screen. The onLoad() method is a great place to change a movie clip's properties (or those of its child movie clips) because we can be sure that the movie clip and any child movie clips that may exist have been fully loaded. This is especially useful when dealing with components, as we shall in later installments of this series.

Next, you're going to alter the Balloon class to make the balloon sail slowly across the screen. You will be using another event handler, called onEnterFrame() to achieve this. Unlike the onLoad() method, which gets called when a movie clip and its child clips have finished loading and a ready to be manipulated, the onEnterFrame() method gets called right before Flash renders a new frame.

If you look in the Document Properties, you will see that the frame rate for your movie is set at 12fps. This means that Flash will try and render updates to the screen 12 times a second. Since the onEnterFrame() method gets called right before Flash renders a new frame, it too will be called roughly 12 times a second. (I say "roughly" and "try" because the actual playback rate may vary depending on how much Flash has to do in each frame. If you ask it to do too many things on a single frame, it may have trouble keeping to the frame rate. We call this "lag".)

So, if you want to move the balloon slowly across the stage, one way of doing it is to increase the _x property by a certain value every frame. Change the class so it matches the one below to see how this can be implemented in ActionScript 2:

ActionScript:
  1. class Balloon extends MovieClip
  2. {
  3. function onEnterFrame ()
  4. {
  5. // Has the balloon reached the
  6. // right edge of the screen?
  7. if ( _x < 330 )
  8. {
  9. // No, make it move right
  10. // by one pixel
  11. _x = _x + 1;
  12. }
  13. else
  14. {
  15. // Yes, remove the onEnterFrame
  16. // event handler (stop animating.)
  17. onEnterFrame = null;
  18. }
  19. }
  20. }

Test the movie and watch the balloon slowly sail from one end of the screen to the other. What will happen if you increase the frame rate in the Document Properties dialog box? Try it and see!

You will notice that we have used a new construct in this example: A conditional expression called if. Conditional expressions (or "conditionals") allow you to make decisions in your code. In this example, you need to check whether the balloon has reached the right edge of the screen. If it has, you need to stop animating it. If it hasn't, you need to keep animating it by incrementing its horizontal location by one pixel. This is what the if statement allows us to do. The general syntax is:

ActionScript:
  1. if ( thisIsTrue )
  2. {
  3. // then do this
  4. // ...
  5. }
  6. else
  7. {
  8. // do this instead
  9. // ...
  10. }

Flash evaluates the expression within the parentheses and, if it evaluates to true, executes the code in the first set of curly brackets. If the expression is false, it executes the code in the second pair of curly brackets instead. Code within pairs of curly brackets, by the way, is called a "block" of code.

The code in this example says: Is my x-coordinate less than 330? If so, then I haven't reached the edge of the screen, so update my x-coordinate by 1. Else (otherwise), delete this event handler method so that further updates are not performed.

Setting a method's value equal to null effectively deletes the function. When Flash calls onEnterFrame() on the frame after the balloon has reached the right edge of the screen, it will not find a function to execute because the current function will have been erased, replaced with a null (empty) value.

In all honesty, we could just as easily have done the following:

ActionScript:
  1. function onEnterFrame ()
  2. {
  3. // Has the balloon reached the
  4. // right edge of the screen?
  5. if ( _x < 330 )
  6. {
  7. // No, make it move right
  8. // by one pixel
  9. _x = _x + 1;
  10. }
  11. }
  12. }

By removing the else clause, we effectively give Flash just one choice. If the x-coordinate of the balloon is less than 330, then increment the x-coordinate by one. What happens if the x-coordinate is equal to or more than 330? Nothing! You haven't told it to do anything in that instance and Flash is awfully bad at improvising – it does what you tell it to, exactly as you tell it to do it – nothing less, nothing more.

So _x will happily increment from 328 to 329 to 330 but when onEnterFrame() gets called next, the expression 330 < 330 will evaluate to false. Flash will thus not be able to execute the first code block and, finding no other code blocks, simply get on with the other things it has to do!

This way of doing things is not as neat as the first method, however, because the onEnterFrame() event handler will keep getting called and the if statement will keep getting executed on every frame, even after _x has reached 330. This is a waste of resources and might potentially slow down your Flash movie. This is why in the first example we remove the onEnterFrame() method once we've reached the end of the animation by setting it equal to null.

By the way, you may be wondering how we arrived at the value of 330. It's the width of the stage (430) less the width of the balloon movie clip (100). Remember that the position of a movie clip is calculated according to its registration point and that the balloon movie clip's registration point was set to the top-left by default.

Conclusion

You covered quite a bit a ground in this tutorial and saw how to link a movie clip to a class and how to extend the built-in MovieClip class to inherit and use its properties and methods.

In the next installment, you will expand upon the Balloon example and learn some better practices. You will also get the chance to replace the scripted frame-based motion you created in this exercise with scripted time-based motion, create some custom properties and constant to clean up your code and learn about another very special method called the Constructor.

I hope you enjoyed this first installment in the Hands-on: Introduction to ActionScript 2 tutorial series. The next installment should be online in about a week or so!

Comments