Chapter 4. Interactivity and Movie Clips

Where do animators find the patience to create entire cartoons by hand using Flash? Well, they don’t. To simplify the process, animators use another type of symbol in Flash called a movie clip. This chapter shows you how to use movie clips to great advantage, and how to control them via ActionScript.

In Chapter 3, we created a simple animation entirely on the main timeline. But what happens when we need to create more complex animations, such as for a cartoon character? A cartoon character usually has several moving parts, such as its mouth, eyes, arms, and legs. If we had to animate the legs every time the character walks and animate the mouth every time the character speaks, it would be very time-consuming. Furthermore, to add variety would require us to create multiple permutations, such as walking while talking versus walking while not talking. In this chapter, we’ll look at how movie clips allow us to create animations that play independently of one another. While creating Box Guy, the unofficial mascot for Flash Out of the Box , we’ll use separate movie clips for his eyes and legs.

Before we begin animating, we need to construct our cartoon character. To do this, we’ll use the Pencil tool, layers, and symbols. Once all the parts are built, we’ll bring the character to life through animation.

Drawing A cartoon Character

The first thing we need for our cartoon character is a body. Since this character will serve as a mascot for this book, we’ll make his body from a box and then add a face and legs. By doing this, we’ll see how the configuration options for the Pencil tool affect the outcome of each drawn line. In more complex situations, you might sketch some character prototypes on paper and create a storyboard for the animation. But here we focus on how to use Flash rather than exploring techniques common in traditional cel animation.

Start With the Body

Let’s start by creating the body for the character. Later on, we’ll create a background image of a street and change the Stage color to sky blue. The character will walk down the street and stop.

First, we have to create a document and configure our Pencil tool:

  1. Open a new, blank Flash document and save it as box_guy.fla in the 04 folder.

  2. Change the Stage dimensions to 550 x 200.

  3. Choose Edit Preferences (on Windows) or Flash Preferences (on the Mac) to open the Preferences dialog box. Choose the Editing tab of the Preferences dialog box.

  4. In the Drawing Settings section of the Editing tab, set the following options to Normal: Connect Lines, Smooth Curves, Recognize Lines, Recognize Shapes, and Click Accuracy. A bug in Flash MX 2004, including the 7.0.1 updater, leaves some of the drawing settings blank by default, which prevents the drawing tools from working properly. This is fixed in the 7.2 update (included on this book’s CD-ROM). These options determine how the Pencil tool behaves as you draw. Click OK to close the Preferences dialog box.

  5. Activate the Pencil tool. By default, the Pencil tool mode—in the Options section of the Tools panel as shown in Figure 4-1—is set to Straighten. (If it’s not already set to Straighten, set it now by clicking on the current option setting.)

  6. In the Properties panel, set the Pencil tool’s stroke color to dark gray, set the stroke weight to 1, and choose Solid for the stroke style.

Now that we’ve got the Pencil tool configured, let’s see what happens when we try to draw a box:

  1. On the Stage, use the Pencil tool to draw a square. To do this, click and drag to draw the first line, release the mouse button (or lift your stylus), then draw the second line, and so on. Notice that each line straightens automatically after you draw it. Unless you’re better at drawing connecting lines than I am, your square probably looks a little messy, so let’s try something else.

  2. Undo several times (or use the history slider in the History panel) to get rid of the lines you just drew.

    The Pencil Tool Options
    Figure 4-1. The Pencil Tool Options
  3. Draw a square again, but this time, draw it in one continuous motion, without releasing the mouse button until the square is complete.

When you release the mouse button, your rough drawing should automatically turn into a square with four straight, connected lines. Flash automatically tries to detect what shape you have drawn, because the Recognize Shapes preference is set to Normal. Flash recognizes that you’re trying to draw a square and helps you out by straightening the lines and converting the corners into right angles. (Flash also recognizes attempts to draw other shapes, such as circles, rectangles, and triangles.) If your square did not straighten, it means Flash could not recognize your drawing as an attempt at a square, so you need to undo and draw it again. It helps if your last line overlaps the first side you drew; otherwise, Flash may not close the gap or recognize the shape as a square. If you are still having trouble drawing a square, consider another career…um… I mean consider getting a drawing tablet. A stylus is often easier to draw with than a mouse is. You’re already using a drawing tablet? Well, then, practice freehand drawing with a pencil and paper until you get better at it.

Of course, you can draw a square using the Rectangle tool, but Flash’s shape recognition feature allows you to draw rectangles with the Pencil tool, too. Therefore, the Pencil tool allows you to draw shapes or sketch freehand without switching tools.

Like most men, Box Guy could use some depth if he’s going to appeal to the other Box People out there. Let’s fill the square with color and turn it into a cube:

  1. Use the Paint Bucket tool to fill the square with the color of your choice. The stroke color is dark gray, so I chose light gray for the fill color to help define the box edges.

  2. Activate the Selection tool by pressing V (not Ctrl-V or Cmd-V, just V), select the fill and stroke for the square, then resize the square to 80 x 80 using the Properties panel.

  3. Alt-drag (Windows) or Option-drag (Mac) the square to duplicate it. Position the copy a little bit above and to the right, overlapping the first square, as shown in the first panel of Figure 4-2.

  4. Use the Pencil tool to draw a connecting line from the upper-left corner of the first square to the upper-left corner of the second square. (To zoom in, activate the Zoom tool—the magnifying glass icon in the toolbar—and click on the Stage until the drawing is easier to see.) Notice that, even with the Straighten option enabled for the Pencil tool, it can be difficult to draw the connecting line.

    Undo. There is an easier way to draw a line.

  5. Select the Line tool from the toolbar.

  6. Use the Line tool to draw a connecting line from the upper-left corner of the first square to the upper-left corner of the second square.

  7. Finally, draw a connecting line from the lower-right corner of one square to the lower-right corner of the other. The result is shown in the second panel of Figure 4-2.

Build A Box From Scratch
Figure 4-2. Build A Box From Scratch

The squares now look like a hollow cube, as seen in the second panel of Figure 4-2, but two of the corners have no fill, and two lines need to be removed to make it look like a three-dimensional box:

  1. Select the top horizontal line of the first box and delete it, as shown in the third panel of Figure 4-2. Be sure not to select the entire stroke.

  2. Select the vertical line on the right side of the first box and delete it as well, as shown in the fourth panel of Figure 4-2. The result is shown in the fifth panel of Figure 4-2.

  3. Add the fill color to the white areas that remain using the Paint Bucket tool to create the cube shown in the final panel of Figure 4-2. Remember, if the fill doesn’t get applied, choose Close Medium Gaps or Close Large Gaps from the Paint Bucket tool options , and try to apply the fill again.

    Delete the Extra Lines to Give the Cube a Box-like Appearance
    Figure 4-3. Delete the Extra Lines to Give the Cube a Box-like Appearance
  4. Select the fill area that represents the bottom of the box and change its color to dark gray. The box now looks as if its bottom panel is missing, as shown in Figure 4-3.

Now we have a body for our cartoon mascot. Soon, we’ll add a face and legs, but the legs should appear to emerge from the bottom of the box. We can place items closer to the foreground or background (called z-positioning or the stacking order) using layers. So let’s separate the front and back of the box, convert them to symbols, and put them on separate layers:

  1. Double-click the fill area of the box in front to select its fill and stroke.

  2. Convert it to a graphic symbol by choosing Modify Convert to Symbol (F8) and setting the Behavior type to Graphic. (Hereafter, we’ll simply refer to these as graphic symbols.) Name the symbol front of box.

  3. Shift-select the remaining fills and strokes of the cube and convert them to a graphic symbol called back of box.

  4. Choose Edit Cut (or press Ctrl/Cmd-X) to cut the back of box instance from the Stage.

  5. Add a new layer to the timeline and drag it underneath Layer 1.

  6. Choose Edit Paste in Place (Ctrl/Cmd-Shift-V) to paste the back of boxinstance on the new layer in the exact location from which it was cut.

  7. Rename the top layer front of box and the bottom layer back of box.

  8. Save your work.

Soon, we’ll draw legs on a layer between the front of box and back of boxlayers, so that the legs appear to emerge from the bottom of the box. First, however, let’s give the character a face.

Putting A Face On the Box

In this section, we’ll create a face using separate movie clips on separate layers for each eye and the mouth.

To add the face to the character:

  1. Add a new layer to the timeline, above the others, and name it face. Doing this first ensures that when you create the eyes and the mouth, they’ll be on the face layer.

  2. Let’s create an oval for each eye. Somewhere on the Stage, use the Oval tool from the Tools panel (a.k.a. the toolbar) to draw a vertical oval about 20 pixels tall. Make sure the fill and stroke colors are both dark gray.

  3. Convert the oval to a symbol and name it eye_mc. Instead of creating a graphic symbol, however, choose Movie Clip for the Behavior type in the Convert to Symbol dialog box. In just a minute, we’ll enhance the eye_mc movie clip symbol to make the eyes blink independently of the animation on the main timeline.

  4. Activate the Pencil tool, and choose Smooth in the toolbar’s Options section. Instead of straightening the lines we draw, Flash will smooth them.

  5. Draw a smile and add a laugh line to each end of the smile line, as shown in Figure 4-4.

    The Face Of The Box Character
    Figure 4-4. The Face Of The Box Character
  6. Alt-drag (Windows) or Option-drag (Mac) the eye_mc instance to create a second instance. Arrange the smile and two eyes to make a face.

  7. Select the two eyes and mouth, and position them over the front of box instance to give the character its face.

  8. Select the two eyes and mouth, and convert them to a movie clip symbol and name it face_mc. We want to group them together into one symbol so they can be positioned as one entity. Frankly, we could use Modify Group instead of creating a symbol if our only goal was to group them together. However, creating a symbol gives you the ability to control the face_mc clip and any clips within it in a hierarchy via ActionScript, as described in the section “Controlling Movie Clips” toward the end of this chapter. For example, you could make the eyes blink or wink randomly, or you could change the mouth position. See the “Movie Clips” sidebar for more information.

In order for the eyes to blink, face_mc’s symbol Behavior type must be set to Movie Clip, not Graphic. Adding the _mc suffix to the end of movie clip symbol names makes them easier to identify in the Library; however, the symbol’s type is determined by the setting in the Symbol Property dialog box, and not by the name’s suffix.

Our character is starting to get a personality, but there’s still plenty to be done.

Using Movie clips To Create Independent Animations

To bring our cartoon character to life, we need to give him some human characteristics, such as blinking eyes.

As I alluded to earlier, movie clips come in handy here because they allow the eyes to move independently of the rest of the character. Thus, Box Guy can walk and blink at the same time, or he can just blink like a proverbial deer in the headlights.

A movie clip acts like a movie within a movie. Each movie clip symbol has its own timeline. Movie clip instances play independently of the main timeline. So, if we create a 25-frame animation on a movie clip symbol’s timeline and place an instance of the symbol on the Stage, it will play even if the main timeline is stopped.

We need the character’s eyes to blink regardless of what is going on in the rest of the animation, so let’s use a movie clip to create a blinking eye animation:

  1. Assuming you are still editing the face_mc symbol, double-click on one of the eye_mc instances to edit its symbol in place. Make sure you’re editing the correct symbol by checking the Edit bar, which should say Scene 1, face_mc, eye_mc. (If the Edit bar says Scene 1, face_mc, the first double-click opened the face_mc symbol for editing; double-click again on an eye_mc instance to edit the eye_mc symbol.) Notice that the movie clip symbol has its own timeline and can contain one or more layers.

  2. Select frame 32 of the eye_mc clip’s timeline and press F5 to add a frame. (Here, we use the term eye_ mc clip for brevity, but it is technically an onstage clip instance of the eye_mc movie clip symbol from the Library. Did you notice the difference and were you able to discern its meaning in context?)

  3. Add a new keyframe at frame 30.

  4. At frame 30, select and delete the fill within the oval. Then, select and delete most of the stroke, leaving only a curved line at the bottom, as shown in Figure 4-5. This makes the eye appear closed, which is part of the blink sequence.

    The Closed Eye For The Blinking Animation
    Figure 4-5. The Closed Eye For The Blinking Animation
  5. Press Enter or Return to watch the animation. When the playhead reaches frame 30, the eye closes for two frames, then stops.

  6. Return to Scene 1 by clicking Scene 1 in the Edit bar, and choose Control Test Movie (Ctrl-Enter on Windows or Cmd-Return on Mac) to see the animation.

There is only one frame on the main timeline, but the eye-blinking animation takes place on the eye_mc clip’s timeline. The eye_mcclips—remember there are two instances of the eye_mc clip symbol on Layer 1 of the face_mc symbol’s timeline—play in their entirety and then loop. So, no matter what the rest of the character is doing in the animation, the eyes continue to blink. This separation of character parts makes movie clips very useful for animators. Once the parts of a character are created, they can be reused whenever necessary. And they can be manipulated independently, so the eyes or mouth can animate independently of the legs. This allows you to combine them in different ways for much more variation without a lot of extra work. For example, if you’re animating a dog, you might use one movie clip to create a wagging tail and a second clip for the dog’s legs. You might then turn the whole dog into a movie clip that can be controlled independently of the dog’s owner (another clip) on the Stage.

Next, let’s draw legs and animate them so we can make the character walk across the Stage.

Drawing the Legs

So far, Box Guy is a bit of a bore. All he does is stand there and blink. We want him to walk across the Stage, so let’s give him some legs, as shown in Figure 4-6. We’ll create a walk cycle—a series of character positions that, when played in sequence, makes the character appear to walk.

  1. Insert a layer between the front of box and back of boxlayers and name the new layer legs.

    The Legs Appear to Emerge From the Bottom Of The Cube
    Figure 4-6. The Legs Appear to Emerge From the Bottom Of The Cube
  2. Activate the Pencil tool and configure it with the Smooth option.

  3. Somewhere on the Stage, on the legs layer, draw a leg with a foot similar to the one in Figure 4-7 and convert it to a symbol. If you prefer, you can open box_guy_complete.fla, located in the 04 folder, and copy and paste the drawing inside the leg symbol. (To enter Edit mode for the symbol, double-click on the symbol icon in the Library.)

  4. Alt-drag (Windows) or Option-drag (Mac) to duplicate the leg (we want him to walk, not hop, so he’ll need two legs).

  5. Shift-select both legs and convert them to a graphic symbol named legs. Then position the legs instance underneath the front of box instance so the legs appear to emerge from the bottom of the cube, as shown in Figure 4-6.

To see our mascot in action, let’s make him move from one spot on the Stage to another and stop. We’ll start by turning him into a movie clip symbol, which makes it easier to control him using the timeline or ActionScript:

The Leg For Our Mascot
Figure 4-7. The Leg For Our Mascot
  1. Select all the parts of the character and convert them into a movie clip symbol named box_guy_mc. Three of the four layers in the timeline are now empty because the entire symbol is contained on one layer.

  2. Delete the empty layers and rename the remaining layer box_guy.

  3. Assign the instance of the box_guy_mc symbol the instance name box_guy_mc in the Properties panel. Soon, we’ll use ActionScript to control this clip, so we must give it an instance name as described in the earlier “What’s in a Name?” sidebar.

We want the character to walk in from offstage left and stop on the right side of the Stage. We do this by placing him at different positions in the starting and ending keyframes and then tweening the animation:

  1. There is always a keyframe in frame 1, so we’ll use that as the starting point for the animation. Select frame 1 and then drag the box_guy_mc clip offstage to the left.

  2. Insert a keyframe at frame 60.

  3. In frame 60, drag box_guy_mc to the right side of the Stage.

  4. Select any frame in the box_guy layer, before the keyframe at frame 60, and choose Motion from the Tween drop-down list in the Properties panel, which causes Flash to tween the character from the starting position to the ending position.

  5. Save your work and test the movie (Control Test Movie).

Okay—so you saw that coming, right? The character blinks and slides from the left side of the Stage to the right, but his legs don’t move and the animation loops back to the beginning. Let’s fix both problems:

  1. Close the Test Movie mode’s Preview window and double-click on the box_guy_mc clip to edit the box_ guy_mc symbol in place.

  2. Select the instance of the legs symbol, which is nested inside the box_guy_mc symbol.

  3. We converted the legs to a graphic symbol earlier, but now we want to animate them, so we need to change the legs symbol’s type to Movie Clip. In the Properties panel, choose Movie Clip from the Symbol Behavior drop-down list. This allows the symbol instance to behave as a movie clip. Assign legs_mc as the instance name for this instance of the legs symbol.

  4. In the Library (Ctrl/Cmd-L or F11), select the legs symbol and click the Information icon, shown in Figure 4-8, to open the Symbol Properties dialog box.

    Click the information icon In the Library to Open the Symbol Properties Dialog Box
    Figure 4-8. Click the information icon In the Library to Open the Symbol Properties Dialog Box
  5. In the dialog box, change the legs symbol’s Behavior type from Graphic to Movie Clip, rename the symbol legs_mc (to help identify it as a movie clip in the Library and to keep names consistent for easy cross-referencing), and click OK to close the dialog box. The symbol is now a movie clip.

Note

Even though we changed the Behavior type of the instance on the Stage in Step 3, we must also change the original symbol’s Behavior type for it to truly become a movie clip. A library symbol can have a different type (as set in the Symbol Properties dialog box) than an instance of the symbol onstage (as set in the Properties panel). Setting different Behavior types for library symbols and their on stage instances can become confusing, but it can also be very handy. For example, if you have a graphic instance on the Stage that you’d like to reposition via ActionScript, you can simply change the Behavior type of the instance to Movie Clip and assign it an instance name.

To finish up, we must animate the legs on their own timeline to create the walking action:

  1. Double-click on the legs_mc instance to edit the legs_mc symbol in place (remember, when a symbol is placed on the Stage, Flash creates a copy of the symbol, called an instance, but double-clicking the instance edits the original symbol from which it is derived). The Edit bar indicates you are now editing Scene 1, box_guy, legs_mc. In other words, you are editing the legs_mc movie clip symbol, an instance of which is located inside the box_guy_mc movie clip symbol, an instance of which is, in turn, located on the main timeline. That is, editing a movie clip in place edits the original symbol, not the onstage instance of the clip.

  2. Shift-select both legs and choose Modify Timeline Distribute to Layers to place the legs on individual layers. Delete Layer 1, which is now empty, and rename the two remaining layers to back_leg and front_leg, with the back leg on the top layer (back leg, in this case, refers to the character’s right leg, which starts in the trailing position).

  3. Activate the Free Transform tool from the Tools panel and select the back leg. Eight handles appear around the bounding box of the leg, as shown in Figure 4-9. Move the cursor over the top handle and, when the cursor appears as a rotating arrow, click and drag to rotate the leg until it’s in a starting position that looks natural for walking. The Free Transform tool can also be used to skew and resize an object on the Stage, which we’ll talk more about later.

    The Free transform tool Displays Handles Used to rotate, skew, or Resize An object On The Stage
    Figure 4-9. The Free transform tool Displays Handles Used to rotate, skew, or Resize An object On The Stage
  4. With the back leg still selected with the Free Transform tool, move the center circle, or anchor point, to the top of the leg. When we rotate the leg again in a moment, it will rotate about its anchor point, like a construction-paper puppet with limbs held together by brass connectors at the joints.

  5. Repeat Steps 3 and 4 for the front leg.

  6. Insert keyframes on both layers at frame 5 and at frame 10. The legs need to rotate from frame 1 to frame 5, then return to their starting position at frame 10. Adding the ending keyframe ensures that the leg positions at frames 1 and 10 match, because a new keyframe always inherits what is on the previous keyframe. By leaving frames 1 and 10 as is, our animation loops seamlessly.

  7. Select frame 5 on the back_leg layer and use the Free Transform tool to rotate the leg again. (You may need to first reposition the anchor point on the leg graphic because we’ve added keyframes since you first set the anchor point.) This time, rotate it so it appears to move from being the trailing foot to the lead foot.

  8. Conversely, rotate the front_leg on the front_leg layer so the foot goes from being the lead foot to the trailing foot (again, you may need to first reposition the anchor point). This alternation of the feet will provide the illusion of walking.

  9. Create a motion tween on both layers, from frame 1 to frame 5, then from frame 5 to frame 10. To select multiple frame spans, select a frame in one of the frame spans, then press Ctrl (on Windows) or Cmd (on Mac) and select a frame in each of the other frame spans. Then choose Motion from the Tween drop-down list in the Properties panel to apply a motion tween to every frame span at once. The timeline should match Figure 4-10.

    The Timeline For Legs_mc
    Figure 4-10. The Timeline For Legs_mc
  10. Save your work and test the movie.

Now the character walks his way from the left side of the Stage to the right side in a fluid motion. The movie clip for the blinking eyes plays independently of the clip for the legs, and both play independently of the main timeline. The animation on the main timeline, however, still loops, causing Box Guy to suddenly jump from the right side of the Stage back to the left side where he started. Next, we’ll use ActionScript to stop the character on the right side of the Stage and stop the legs from moving. We’ll leave the eyes blinking periodically.

Controlling the Character With Actionscript

As we saw in Chapter 3, we need to add a stop() action to the main timeline to prevent the animation from looping. (The words action and command are often used interchangeably; both refer to an instruction programmers write in ActionScript to tell Flash what to do.) In addition, we need to tell the legs to stop moving when the character is standing still. To do this:

  1. Close the Preview window and return to Scene 1 (using the Edit bar).

  2. Add a new layer to the main timeline and name it actions. Remember, it’s good practice to keep all ActionScript on its own layer so it’s easy to find.

  3. Add a keyframe to frame 60 on the actions layer.

  4. Open the Actions panel (Window Development Panels Actions or F9).

    Note

    In the Script pane of the Actions panel, add the command stop(); on frame 60. This causes the main timeline to stop animating once frame 60 is reached. As a best practice, you should include the semicolon after stop() to signify the end of the command. In simple cases such as this, the semicolon is optional because Flash can guess where the end of the command is (as indicated by the carriage return at the end of the line). But commands can be split onto multiple lines, making it harder for Flash to guess where the command ends, so it is good practice to include the semicolon at the end of each command. As a general rule, if a command is broken onto multiple lines, the semicolon belongs at the end of the last line. We’ll talk more about semicolons in Chapter 7.

  5. Although the main timeline will stop, the legs will keep animating because the legs_mcclip has its own independent timeline. Press Enter or Return to insert a blank line in the Script pane and add the following ActionScript to make the legs stop moving: box_guy _mc.legs_mc.stop();.

This last line of code, added to the main timeline, is simply another stop() command, but it’s targeted at the legs_mc instance located inside the box_guy_mc instance.

Remember that clips exist in a nested hierarchy, starting from the main timeline. The dot operator (a period) is used to build the path to the intended target clip, much as slashes separate folders in a directory path. In this case, box_guy_mc.legs_mc.stop(); tells the Flash Player to look for the legs_mc clip inside the box_guy_mc clip on the main timeline and stop its playback.

Note

ActionScript can’t control a movie clip instance unless you first give it an instance name using the Properties panel. Therefore, you must assign an instance name to any movie clip you intend to access or control through ActionScript.

To ensure the movie clips containing the box character and his legs are controllable via ActionScript, we assigned them the instance names box_guy_mc and legs_mc using the Properties panel when building our project.

So now Box Guy walks across the Stage and stops (and his legs stop too).

Creating the Background

Before we publish the movie, let’s create a background graphic, so the character appears to be walking down a street like the one in Figure 4-11.

  1. Add a new layer, name it bg(short for background), and drag it beneath the other two layers.

  2. Drag the playhead to frame 1, so the character isn’t in the way as we draw the street.

  3. On the Stage, draw a gray rectangle that occupies the bottom half of the Stage. Delete the right, left, and bottom lines of the stroke. We don’t need them.

  4. Select the remaining stroke, along the top edge of the rectangle, and change its stroke style to Ragged (the third choice in the Stroke Style drop-down list in the Properties panel). Set the stroke color to dark gray.

  5. Next, we need to add yellow lane-divider markings to make it look like a street. Activate the Line tool, set the stroke color to yellow, and set the stroke style to Dashed. Set the line thickness to 5.

  6. Click the Custom button in the Properties panel to open the Stroke Style dialog box. Beneath the Type drop-down list, enter 40 into the fields that set the length of each dashed line and the distance between the lines. Click OK to close the dialog box.

  7. Draw a line from one side of the Stage to the other, in the center of the rectangle. Now we have a lane divider, such as we see on a typical street, as shown in Figure 4-11.

    The Completed Street Background
    Figure 4-11. The Completed Street Background
  8. Shift-select all the parts of the street graphic and convert them to a graphic symbol named street.

  9. Finally, change the background color of the Stage to sky blue. Remember, to do so, click once on the Stage and then click on the Background color swatch in the Properties panel.

  10. Save your work.

  11. Choose File Publish to generate a completed .swf file.

  12. If you have been following along (and I hope you have), box_guy.swf, located in the 04 folder, shows what your completed movie should look like.

Our movie is complete! The character walks from one side of the Stage to the other, blinking the whole time, and stops. When he stops walking, his legs stop moving, but he continues blinking, giving the character a lifelike quality.

Nesting movie clips within other clips is common in Flash development, as is using multiple clips within one project. Clips can be nested multiple levels deep (a clip within a clip within a clip). For example, the face clip can contain two instances of the eye_mc clip, plus a mouth graphic, and the entire face clip can be nested within the box_guy_mc clip. A movie clip can be used for an animated logo on a Flash web site, as a container for video in an interface (which we’ll construct later on), and even as a menu system, similar to those made with JavaScript in traditional site design.

Controlling Movie Clips

Movie clips can be assembled to create independent animations and controlled through ActionScript, as we saw in the last section, in which we used a stop() command to stop the animation of Box Guy and his legs. We can also allow the user to control the movie clips if we implement the necessary functionality and a user interface to control it. For example, we can tell Flash to restart the animation when the user clicks on the character. To accomplish this, we add an event handler to our ActionScript. An event handler tells the Flash Player, “When an event—such as the user clicking on the character—occurs, perform the following action(s).” In this case, the desired action is to replay the animation. How do we do this?

Whenever the user clicks on Box Guy, we’ll send the playhead back to frame 1 and restart the main timeline and the legs. To restart the animation:

  1. On frame 60 of the actions layer, add the following code using the Actions panel. This is our event handler. The onPress() event handler tells Flash to perform this action when the user clicks the mouse on the specified clip (in this case, box_guy_mc):

    	 box_guy_mc.onPress = function () {
    	   gotoAndPlay(1); 
    	   };
  2. Add a play() action to the event handler to restart the animation of the legs from where it last left off (changes shown in color):

    	box_guy_mc.onPress = function () {
    	  gotoAndPlay(1);
          this.legs_mc.play();
  3. Save your work and test the movie.

  4. When the character stops walking, click on it to replay the animation.

The script you wrote sets up a function that runs when you click on the box_guy_mc clip in the movie.

Note

Note that, as a best practice, we placed this code on the main timeline, not the clip’s timeline. Therefore, the clip names are relative to the main timeline. To refer to a clip nested within a clip, we can use an expression that specifies a complete path (known as targeting) down the hierarchy.

In some situations, the best practice is to place ActionScript in external .as files (in fact, this is required when writing custom ActionScript 2.0 classes). For details on ActionScript 2.0 best practices, see Essential ActionScript 2.0(O’Reilly).

A function is a reusable set of actions that Flash can perform, grouped into one conveniently named command. A function in ActionScript is similar to a function in real life. For example, my brain’s getCoffee( ) function includes actions to find a coffee cup, pour coffee into it, and drink the coffee. My getCoffee( ) function is built into my brain and I don’t have to think about it (and believe me, if I had to think about it—I’d just stay in bed). The code in my brain looks like this:

	me.getCoffee = function () {
	  findCoffeeCup();
	  pourCoffee();
	  drinkCoffee();
	}

My brain knows to do all these things when the getCoffee() function is run, so all I need to do now is tell my brain when to run the function. To do this, I’ve programmed an event handler for myself:

	me.onAlarm = function () {
	  getCoffee();
}

When the alarm goes off, my brain runs the getCoffee() function, which then performs the necessary actions to achieve the desired goal: to get caffeine into my bloodstream!

Functions can invoke (run) other functions by specifying the name of the function followed by the () operator. Notice that getCoffeee() invokes several functions—findCoffeeCup(), pourCoffee(), drinkCoffee()—whose contents are not shown.

Simplifying Code

Since the onPress() event handler is on the last frame of the animation, we don’t actually need to tell the Flash Player to go back to frame 1. We only need to tell it to play, and it will pick up where it left off. Because the animation is already on the last frame, the playhead will automatically loop back to frame 1. Let’s modify the code as follows:

  1. Replace gotoAndPlay(1) with play() as follows (changes shown in color):

    	box_guy_mc.onPress = function () {
    	  play();
          this.legs_mc.play();
    	};
  2. Save and retest the movie. When the character stops walking and you click on it, the animation replays.

Get Flash Out of the Box now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.