You are on page 1of 211

Flash MX 2004 fast & easy web development

By Michael Puleio, Jennifer Turner Long

Ripped by: Lilmeanman

Lilmeanman

Digitally signed by Lilmeanman DN: CN = Lilmeanman, C = US, O = Lilmeanman UNltd, OU = Lilmeanman UNltd Reason: I am approving this document Date: 2004.08.31 20:30:41 -06'00'

About the Authors


Michael Puleio started programming in BASIC on a Commodore 64 at the age of nine. Since then, fascinated by the power and capabilities of computers, he has used a number of programming languages and other tools to create software, including Pascal, FORTRAN, Visual Basic, C/C++, Java. C#, Active Server Pages, and Macromedia Flash. In addition, he has been a systems administrator and developed Web sites for small companies and large universities. He also worked as a software engineer on projects ranging from airline reservations to geophysics tools. In his spare time, he enjoys playing computer games, reading, and spending time with his wife. Jennifer Turner Long is a Web developer for an IT services company that supports organizations in the senior health care industry. She has worked in a variety of roles, including project management and network administration, in addition to Web development. Outside of programming languages, she enjoys working with a number of tools including Macromedia's Flash MX and Fireworks, as well as Adobe's Photoshop and Premiere, to create cool graphics and multimedia. She lives in Pennsylvania with her husband and her maroon-bellied conure. In her spare time she enjoys gardening, dancing, and reading.

Introduction

Macromedia Flash MX Fast & Easy Web Development from Prima Tech is designed to help new and intermediate users become familiar with basic and intermediate features of Flash MX. Using a simple step-by-step, visual approach, this book introduces the tools and features of Flash MX. It shows how they are used, and provides examples along the way. With this book, you can learn how to create professional looking movies that will add life to any Web page. Flash's extreme popularity comes from its small file sizes and accessibility. Flash has the capability to take an amazing animated movie and compress it into a size small enough for use on the Internet. Compared to video streaming, Flash is a much more efficient and effective way to package material. Also, Flash movies are easily played on almost all computers. Many computers come packed with the Flash plug-in, and it is an easy download for those machines that do not. Flash is the industry standard of its field. Most people know that Flash is a great tool for creating "eye candy," but Flash's capabilities are not just graphical in nature. Flash's native scripting language, ActionScript, is quite robust and more and more Flash applications that work with data use it.

Who Should Read This Book


This book is for those people who are new to Web design and development, as well as those who have been working in Web development for a while. Contrary to popular notions, you don't have to be an artist to create elegant, image-driven Web pages. If you are familiar with Windows or Macintosh computers and want to add excitement to Web pages, this book is for you. The illustrations in this book focus on the Windows version of Flash MX, but the Macintosh version looks more or less identical. The commands should be similar as well, and in most cases both commands are included in the text. There are four main sections to this book.

The Basics of Flash


This section provides background information on Flash and its role on the Internet. It introduces all of the tools used in the Flash workspace and provides step-by-step instructions as to how these parts fit together and flow into a movie.

Animation
This section advances your learning into the realm of motion. It introduces the different methods of creating motion in Flash and shows you how to apply them. Look for some pretty neat looking tricks demonstrated in this section!

Sound
Sound on the Internet is an interesting topic. This section provides necessary background information about sound and how it works. It teaches you how to use Flash's compression tools to yield the smallest sound file with the highest quality sound possible.

Finishing Touches
This section helps you put what you've learned together and introduces you to advanced concepts. It introduces HTML and shows how Flash works in HTML. You will learn how to publish a basic Web page and how to embed your Flash movie in it. ActionScript is introduced in this chapter, and you'll learn the building blocks of this scripting language with hands-on examples.

Helpful Hints with Every Chapter


Whether you have a Windows or Macintosh computer, and regardless of what you already know about Web development, you can enjoy learning about Flash MX the fast and easy way. NOTE Tips offer hints, explain more about a special feature, and tell you how to use a shortcut to boost your productivity to make work fun. NOTE Cautions warn you about potential pitfalls, explaining what might be happening and offering alternative routes you can take. NOTE Notes provide additional information about a feature, or extend an idea on how to use a feature.

Part I: The Basics of Flash MX


This section starts with the fundamentals of Flash and prepares you to put components together into production. You will gain background information on Flash and its current role on the Internet. All the contents of the toolbox are thoroughly explained with examples demonstrating how to use each one. Finally, you will learn about the Flash workspace and create your first movie.

Chapter 1. Getting Started with Flash MX


In this chapter, you will learn the answers to these questions:

What can Flash do? What are the new features in Flash MX? How can the development process be organized?

The Internet has exploded in recent years from a small computer network for academic researchers to an immense medium for commercial ventures, including entertainment, education, shopping, advertising, and just plain expressing yourself. Early Web sites were composed of static text pages containing basic text links. These pages were very simple andto today's Web-savvy eyeprobably pretty boring. At this early stage, the Web was about conveying information. Web sites now differ greatly, providing a sensory overload at times, from pop-up advertisements to complex graphics to motion on many pages.

With the advent of the commercial Internet, Web developers looked for ways to make sites more interesting in an effort to draw more people to their sites and to make money. Graphics became widely used, enhancing the design of pages. Scripting and interactivity were created, allowing Web sites to gather input directly from their viewers. Multimedia content soon followed, enabling video and audio to be placed on the Web.

What Flash Can Do


Macromedia has created a tool to assist Web developers with creating interactive, dynamic, eye-grabbing sites. Using Flash, developers can animate graphics, add sound, and create movies, just to name a few possibilities. From the simplest image movement to a complex movie clip, Flash can help you create the look you want. Flash also contains a powerful, native scripting language, named ActionScript, as discussed in Chapter 12. ActionScript can assist you with anything from automating tasks to adding data-driven functionality to your site. As you work through this book, you will gain hands-on experience about Flash's capabilities. You will create symbols and buttons, learn about animation and the Timeline, and produce a complete movie clip.

Macromedia Flash MX
The most recent tool from Macromedia is Flash MX. This new tool for developers simplifies the process of creating Web sites that interact with visitors and include a multimedia experience. Flash MX (also known as Flash 6) builds on the previous generation of tools by adding new features and improving existing features. These features include the following information:

Video. Flash MX supports most common video formats. Multiple languages. Flash MX is available in 11 different languages. Multiple platforms. Flash Players are available for major Web browsers on most popular computer operating systems. Flash movies can be created once and viewed on almost any computer. Scripting. Flash MX includes a full-featured scripting language, ActionScript, to aid in interactive design, to control navigation, and to enable user interaction. Flash and ActionScript have been used to create Web sites, greeting cards, and video games. Built-in components. Flash MX includes a number of components that simplify the design of user interfaces. Text input fields, buttons, and check boxes are examples of these components that can easily be added to a Flash movie.

Macromedia Flash is a standard platform for Web designers and Web developers because of the flexibility and power of the platform. You can feel confident that the vast majority of computers being used can view Flash files with no download. And, when the Flash player does need to be downloaded, the process is quick and simple.

Organizing the Development Process


Before diving into the details of Flash, I need to cover a few basic ideas behind the development process. You're probably thinking, "Why do I need to know some process?" The answer is simple: Creating a Web site can quickly go from being a simple project to a horrible disaster if you don't have a plan.

Let's look at an example. Bob is a Web developer for a small but growing company. His boss tells him that the company Web site needs to be redesigned so that it looks better. Bob likes a challenge, so he dives in. A few weeks later, he emerges from his office after publishing the new site. His boss looks at it, and Bob now has a to-do list as long as his arm of changes to be made to the site. Bob makes the changes, publishes the updated site, and tells his boss. The boss is happy, so Bob tells him to check out the site. This process results in another list of changes Bob needs to make. Of course, while Bob is working on this new list, people start talking about the site, and he ends up with instructions from several different high-level executives telling him how the site should work. Unfortunately, two of his instructions, from different vice presidents, are "Get rid of the graphics on the site" and "We need more graphics on the site." Bob is now in a no-win situation, but he works long hours and begins to burn out trying to keep everyone happy. In the end, he is fired not because he was a bad developer, but rather because his requirements were not identified at the beginning. Bob didn't need to have his project spiral out of control. A number of processes are out there, and several books describe them. For simplicity, I'll show you a simple, condensed design process. In this four-step design process, you will learn how to: 1. 2. 3. 4. Gather requirements. Design. Develop. Review.

Simple, right? Let's look at each step in detail from the perspective of developing a Web site. You can easily apply the same process to application development or moviemaking.

Gather Requirements
This step is the process of finding out what needs to be done. It can be as simple as creating a small, one-page site that lists a company name, address, and phone number, or it can be as complex as an e-commerce system for selling 10,000 products in 12 countries. Of course, you need to gather these requirements from the decision-makers who have a stake in the projectthe CEO of a company or maybe just you, depending on the site. From this list, make sure that you know the answer to the following questions.

Who is your intended audience? Audience identification is crucial during the initial stages of a project. For example, a site designed for an association representing senior citizens looks very different from a site designed to sell products to teens. What is the purpose of the site? Is the site's primary purpose to convey information, complement a marketing strategy, or sell products? Again, the differences are significant. What are the decision-makers' expectations in terms of general look and feel? Are they comfortable with blinking objects, or is subtle movement preferred? Do they have a classic design in mind or something eyecatching? How should the navigation work? What is the general organization of the site?

After you have some foundation knowledge in these areas, you're ready to move to the next step.

Design
Now that you know what needs to be done, you can figure out how to do it. The design process often includes sketches, prototypes, and storyboards. Each situation is different, and each designer is different. Find what works best for you. The important part of the design phase is figuring out how to accomplish each requirement. For most Web site design

projects, the design usually ends with a storyboard that shows not only the different pages in the site but also the connections and links between pages. The design also shows the interface to any back-end databases, accounting systems, or what-have-you. This is your opportunity to put those creative juices to work and illustrate how the entire site flows.

Develop
Now that you know what needs to be done and how it will get done, you have to actually do it. In this stage, you build the site. This subject is what most of this book covers: the mechanics of building graphics, buttons, movie clipswhatever you wantin Flash. Often, you'll discover that you missed an important piece of the design of the project and must revise it before the project can be fully developed. Don't worry: This situation is normal. The design of a big project is usually a living, breathing, changing document.

Review
In the review stage, you compare the site that was developed with the design and its requirements. Test, and then test again. Create as many different environment variables as possible (for example, different browsers, different monitor resolutions, and Macintosh-versus-PC) so that you have a solid idea of which audiences can access your site and are prepared for those questions when they come your way. If you have missed something, this stage is where mistakes are caught. Update the design as needed and fix any problems (usually called bugs) that appear in the development process. When everyone is satisfied that all the requirements are met, publish the site and congratulate yourself on a job well done. This design process is a simple, but powerful, tool. Now that you have some background information and organizational tools, take a look at Flash MX.

Chapter 2. Understanding the Flash Workspace


The first time I saw the Flash workspace, I was almost overwhelmed by all the different windows, panels, and toolbars on the screen. I didn't know where to start, so I stopped and looked at the screen in sections. Let's do that now, starting with a broad overview and then dealing with specific tools. In this chapter, you will learn the answers to these questions:

What are the different parts of the workspace? How can you hide, show, and move panels? How can you use each tool in the Toolbox?

Overview
Here is a quick tour of the default workspace in Flash MX:

Moving, Hiding, Closing, and Opening Panels


All the panelsthose visible by default and those hidden dock with the workspace. Dockable panels or toolbars want to cling to the edges of the screen, but you can move them around. To move a panel, follow these steps.

To dock a panel again, follow these steps, but in Step 3 move the panel toward the edge of the workspace. A darkened border appears, showing where the panel will reside after you release the button.

Closing a panel involves right-clicking in the panel's name and choosing Close Panel. Not all panels are visible by design. Flash MX just has too many to show at one time. If you need a panel that is not visible on the screen, choose the name of the panel from the Window menu. The panel will appear in the workspace.

One problem with so many different panels being available is that the workspace can quickly get too cluttered to work in. If this happens, you can restore the workspace to the default configuration by selecting Window, Panel Sets, Default Layout. NOTE In the screen shots for this book, all the panels are hidden unless they are necessary to show an idea. NOTE CREATING A NEW MOVIE When Flash runs, it automatically creates a new movie for you. Sometimes, you have to create a new movie yourself, by either choosing New from the File menu or pressing Ctrl+N or +N on a Macintosh computer.

The Toolbox
The Toolbox contains many tools, each of which has its uses in the right situation. Rather than explain the tools in the order in which they appear, I discuss them by topic. The different groups of tools in the Toolbox are Selection tools, Drawing tools, Editing tools, View tools, and Color tools.

Selection Tools
Flash has three selection tools: the Arrow Tool, the Subselection Tool, and the Lasso Tool. The Arrow Tool The Arrow tool allows you to choose which objects or parts of objects you want to edit. You can use the Arrow tool in one of two modes. The simple way to choose objects is to click on them.

You can optionally hold down the Shift key and select multiple objects or press Ctrl+A ( +A for the Mac) to select all objects. The second way to use the Arrow tool to choose items is by clicking and dragging a rectangle around the item. 1. Choose the Arrow tool from the Toolbox. 2. Move the mouse to the upper-left corner of the object or objects you want to select. 3. Click and hold the mouse button. 4. Drag the mouse until the selection rectangle includes all the items or parts of items you want to choose. 5. Release the mouse button. You can also use the Shift key to select multiple areas. NOTE Remember that most shapes you draw are composed of several pieces: Each side of the polygon is a piece, as is the fill. Deleting Objects Sometimes, you may find it necessary to delete an item, object, or shape. 1. Choose the Arrow tool from the Toolbox. 2. Click on the item you want to delete. 3. Press the Delete key on the keyboard. The Subselection Tool The Subselection tool allows the manipulation of objects. It has two modes. The first mode has a small filled square next to the mouse pointer, and it is used for selecting and moving objects. The second mode, indicated by a small hollow square next to the mouse pointer, is used to manipulate the vertices of the selected object.

The Lasso Tool The Lasso tool is used for the fine selection of pieces of a drawing.

Drawing Tools
A number of tools for creating art are in the Toolbox.

The Line tool The Pen tool

The Pencil tool The Brush tool

The Line Tool Start by drawing a few lines on the Stage.

The Pen The Pen is a complex tool. You can use it in several different ways, each of which creates different results. The first use of the Pen draws straight lines.

You can also play connect-the-dots. This technique allows you to draw a line from Point 1 to Point 2, another line from Point 2 to Point 3, and another from Point 4 to Point 5 (as many as you want) before ending with a double-click. For example, to draw the letter Z, you would do the following:

Drawing simple shapes with the pen is also possible.

Another way to draw with the Pen tool is to draw curves. This technique is a little tricky and takes a bit of practice.

The Oval Tool Flash has a special tool in the Toolbox for drawing ovals and circles: the Oval tool. Before I show you how to draw ovals and circles, you probably should understand how Flash sees these shapes. An oval in Flash is composed of several curves defined by a bounding rectangle. These curves are drawn from the center of one side of the rectangle to the center of the adjacent side, hitting each side at a tangent. (It sounds more confusing than it really is.) NOTE In Flash, shapes are composed of two elements: an outline and a fill. The outline is the line around the outside of the shape, and the fill is the inside part of the shape. You can choose separately the colors for solid outline and the fill.

Drawing an Oval Follow these steps to draw an oval:

Creating a Circle A circle is a special type of oval that has a square for its bounding rectangle.

The Rectangle Tool Drawing rectangles is simplejust follow these steps:

The Pencil The Pencil tool allows you to draw freehand whatever you want on the screen.

The Brush The Brush tool allows for numerous effects, depending on what options you choose.

Brush mode determines what happens when you paint on the Stage with the Brush tool.

Paint Normal. Paints wherever you move the mouse while the button is held down. Paint Fill. Covers the fill part of objects, but leaves the outlines alone. Paint Behind. Paints behind objects on the Stage. Paint Selection. Paints the selected object or objects. Paint Inside. Paints inside and only inside whatever object you start painting in.

The Text Tool


The task of adding text to a movie is simple. You can choose from three types of text: Static, Dynamic, and Input. For this section, we work with only Static text. Dynamic text and Input text are introduced in Chapter 12, "Simple ActionScript." Adding Static text to a movie is simple, but you have lots of options.

While you are typing text, you can set some options for individual characters.

Choose which font you want to use. Pick a font size by either typing a number in the box or selecting a size from the dropdown list. Use the color selector to choose a color. Select Bold or Italicized text by clicking on the appropriate button. Choose whether a line of text should be aligned to the left, center, or right of the text box, or even justified. Determine how much space appears between each character. Create subscripted or superscripted text.

Decide whether Flash should use a font's built-in kerning. Kerning is a built-in part of a font that determines how much space a specific character will occupy when it is next to another specific character. Select the Format button to set paragraph properties, including indent spacing, line spacing, and margins. Create a hyperlink by typing a URL (Uniform Resource Locator) into the URL Link box.

NOTE USING UNDO Occasionally, everyone makes mistakes. In Flash, you can usually fix those mistakes as you make them by choosing Edit, Undo. This command undoes the last action you did. If you need to undo more than just one action, you can select Edit, Undo more than once. If you make lots of mistakes, you can use a keyboard shortcut, Ctrl+Z or +Z, rather than go through the Edit menu.

Editing Tools
The Free Transform Tool The Free Transform tool allows you to change any object you want. Not only can the characteristics of the object be changed in the Properties panel, but the Free Transform tool can also resize, rotate, skew, distort, and shape.

The different modes include:


Move. Move an object by clicking and dragging the object to the desired location. Resize. Change the size by clicking on and dragging a corner or the center of a side of the selected object. Rotate. Rotate objects by clicking and dragging near a corner, when the rotation icon (a partial circle with an arrow) is visible. The object rotates around the center dot. You can move this dot by clicking and dragging it. Skew. You skew an object by clicking and dragging on a side between the markers on the bounding rectangle.

The Transform Fill Tool When an object has a gradient or a bitmap as its fill, the Transform Fill tool manipulates the fill.

Gradient Fills Gradients are fills that start out as a solid color and end as another color, with shades of the two colors mixed in between. You can use two types of gradients: linear and radial. Linear gradients change from the first color to the second color along a line, and radial gradients change from a point outward in a circle. This explanation is a little tricky, but seeing a gradient helps. To change an existing fill to a gradient, follow these steps:

Bitmap Fills Bitmap fills use a bitmap graphics file instead of a solid color to fill in a shape. Bitmap fills require that a bitmap exist and that the location of the file be known. Bitmaps can be created in Paint, Microsoft's simple graphics creation tool, or created from a Flash movie using File, Export Movie and selecting Bitmap as the file type. To change an existing fill to a bitmap fill, follow these steps:

The Ink Bottle Tool The Ink Bottle tool can change the color of lines, outlines, and pen strokes.

The Paint Bucket Tool Whereas the Ink Bottle tool is used to change strokes, or outlines, the Paint Bucket tool is used to change fills. The Paint Bucket tool changes any fill, including gradients and bitmap fills, to the color you choose.

The Eyedropper Tool The Eyedropper tool is used to select colors from those already used on the Stage. The Eyedropper is also somewhat intelligent, so if you pick a color that was used for fills, it automatically chooses the Paint Bucket tool and you can use the selected color immediately. Using the Eyedropper is simple.

The Eraser Tool Not surprisingly, the Eraser erases. You can set a few options to determine exactly what gets erased when you use the eraser.

When the Eraser is activated, you use it by clicking and dragging over items on the Stage. The different modes for erasing are:

Erase Normal. Erase everything that the mouse pointer passes over. Erase Fills. Erase only fills. Erase Lines. Erase only lines. Erase Selected Fills. Erase only those fills that were previously selected with the Arrow tool. Erase Inside. Erase only items that are inside the object you first clicked in.

To erase entire objects, outlines, or fills, click on the Faucet icon. The mouse pointer becomes a faucet, and any item you click is erased.

The View Tools


The Toolbox has two tools in a small section labeled View. The Hand Tool

The Zoom Tool The Zoom tool scales the Stage to the perspective you want so that you can concentrate on the big picture or on minute details.

Color Tools
The color tools provide many selection options. You can pick from the default range of colors or create your own custom color.

Chapter 3. Flash Workflow


Understanding how the separate components of Flash movies fit together is important. This knowledge benefits your organization and enhances your hands-on skills. In this chapter, you will learn the answers to these questions:

What is the Stage? What is the Timeline? How do you change the properties for a movie? How do you use the Movie Explorer? How do you use scenes?

The Stage
The Stage is the central part of the Flash workspace, where the bulk of the work in creating animations is done. Think of the stage as your scratch pad. You will use it to create the components of your movie as well as to lay out the actual movie itself. The Stage has several tools built into it. The first tool to note is the Zoom tool, in the upper-right corner of the Stage. The Zoom tool allows you to change the view of the stage. If you are working on a large movie and only part of it fits on the screen at a time, this tool is invaluable. Options available from this dropdown menu include the following:

The Timeline
The Timeline Panel, usually located at the top of the Flash workspace, shows vital information about your movie. It displays your frame-by-frame account of what is occurring in your movie. Before I can discuss the timeline, though, you must understand how animations are created. Flash animations are a series of pictures shown rapidly in order. Each picture is a frame, and several frames are displayed every second. I know that this description is simplified, but Chapter 7, "Animation with Motion Tweening," includes a full explanation. Here are a few things to note about the Timeline:

Several important pieces of information are listed below the Timeline:

Some buttons on the Timeline allow for editing the movie in a few special ways:

The area to the left of the Timeline contains controls for editing and displaying layers. When new layers are added to the movie, they go on top of the existing layer. Flash, when using the default settings, will read your movie from bottom to top. Layers are a topic for an entire chapter, but for now you can think of them as a way to organize the objects in a movie. The different buttons in the Timeline that deal with layers are:

I know that some of these descriptions are a little obscure, but most of your questions are answered in Chapter 4, "Layers."

Movie Properties
Flash movies or animations have a number of properties. These properties apply to the entire movie or document depending on what is selected. When the Properties panel is visible and no objects are selected, the Properties panel shows information about the entire movie or document. These properties include:

You can access document properties by clicking on the button that displays the movie size in the Properties panel or by choosing Modify, Document.

The Movie Explorer


The Movie Explorer is a panel that shows the different parts of your movie in an organized fashion, including scenes, objects, sounds, and ActionScripts. That may not seem important now, but for big projects this feature is very helpful because you get an overview of the project. To see the Movie Explorer, choose Movie Explorer from the Panels menu. By default, the Movie Explorer shows only information about the current scene. To show the component parts for all scenes, right-click on the Movie Explorer panel and choose Show All Scenes. The Movie Explorer has several buttons across the top that filter out unwanted information. When a button is selected, the information associated with it is shown. The types of objects that can be filtered out include:

The Frames and Layers option is probably one of the most useful because it shows what objects are where in the movie.

A useful feature of the Movie Explorer is that when an object is selected in it, the path to that item is displayed in the bottom of the Explorer panel. The path contains the scene name, the layer name, the frame number, and the type of object so that you can easily find objects.

Scenes
Movies in Flash, just like movies in Hollywood, are organized into scenes. Each scene usually has a coherent theme or contains one discrete part of a movie. For interactive movies, one scene often contains the response to one type of user action. For example, if a user clicks on one button, the movie plays a certain scene; if the user clicks on a different button, a different scene plays. Part of the planning stage in the design of your movie should include scene organization. When a new scene is added to a movie, it contains one layer and one frame. To switch between scenes in a movie, use the Scene Selector in the Stage. Scenes can also be manipulated in the Scene panel. To show the Scene panel, choose Window, Scene.

From the Scene panel, you can:


Add a scene. Delete a scene. Copy a scene. Rename a scene. Change the order of scenes in the movie.

To delete a scene:

Of course, if you would prefer a simpler solution, you can also delete a scene by doing the following: 1. Choose the scene you want to delete from the Scene Selector on the Stage. 2. Choose Remove Scene from the Insert menu. A dialog box opens to confirm that you do want to delete the scene. 3. Click on OK in the confirmation dialog box. To make a copy of an existing scene, use the Duplicate Scene button on the Scene panel. You can rename a scene by following these steps:

The Scene panel is important because the order in which the scenes are shown is the order in which they are played. To rearrange the order of scenes in the movie: 1. Open the Scene panel. 2. Click and drag the movie you want to move to a new position in the list.

Chapter 4. Layers
Chapter 3 introduced the concept of layers as a way to organize the objects in your movie. As you may have guessed from that brief description, layers can be very helpful in production. In this chapter, you will learn the answers to these questions:

What is a layer? How do you work with layers? What are the properties of a layer? How can you organize layers?

What Is a Layer?
You can think of layers as transparent sheets, like transparencies for overhead projectors. These transparent sheets can contain text and illustrations. A group of sheets can be stacked one on top of another so that you can see the contents of each, but more importantly so you can see the composite of all the sheets. Flash uses layers for organizing and separating different pieces of a movie. For example, you can have a background on one layer, foreground objects on another, a moving object on a third, and text on a fourth. This example shows each layer containing objects that serve a different purpose, which is a good way to think about layers as you get started. Separating your objects onto layers makes the editing process much easier. As you will learn in this chapter, you can hide layers you are not working on so you can see only the one you want to edit. NOTE When adding actions to your movie, it is a good idea to create a separate layer just for them. Keep all of the actions together in one place.

How Do You Work with Layers?


Working with layers is integral to the Flash process. This list shows the basic tasks you can perform with a layer:

Add a layer. Change the layer's name. Add objects to a layer. Delete a layer. Hide a layer. Lock a layer. View layer outlines.

Adding Layers
Because adding layers is such a regular task in Flash, it is quite easy to do.

A new layer appears in the list of layers. Optionally, you can select Layer from the Insert menu. As mentioned in Chapter 3, new layers are added to the top of the list (or above the layer that is highlighted). You may need to scroll down once you have several to see your initial layers. NOTE Each and every moving object in your movie should reside on its own layer. There is no limit to the number of layers you can add.

Changing a Layer's Name

Double-clicking on the name of a layer changes the name into an edit box, where you can type a new name and then press Enter. Consider naming layers according to their function or along a common theme.

Adding Objects to a Layer


After you have more than one layer in your movie, you need to decide what objects should be placed on what layer. To add an object to a specific layer:

Deleting Layers
As the project progresses you may discover a need to organize the movie differently. In this case, you may need to delete a layer. To delete a layer:

A movie must have at least one layer, so if only one layer exists, this option is grayed out.

Hiding a Layer
When a movie contains more than one layer, the objects on all layers are visible on the Stage by default. This feature makes it simple to position objects relative to one another, but the Stage can get cluttered. Flash has a mechanism for hiding individual layers so that the Stage is less cluttered. Hide layers that are not currently being worked on to create more space on the stage. You can look at the Layer area of the Timeline as though it were a spreadsheet with rows. Think of each layer as a row. Think of the dots beneath the properties as columns.

Notice that a hidden layer has an X through both the dot that was clicked on to hide it and through the pencil icon. The X under the eye icon indicates that the layer is hidden. The X through the pencil icon indicates that the laye cannot be edited.

Locking a Layer
When you have a movie with more than one layer in it, which is usually the case, you can inadvertently make changes to a layer you have finished. To avoid this situation, lock layers that are complete. A locked layer cannot be changed unless it is intentionally unlocked.

Viewing Layer Outlines


Things can quickly get cluttered with numerous layers on the Stage. In some situations, however, completely hiding the layers doesn't work because you need to be able to see, for reference, where objects reside in the context of the stage. To deal with situations like this one, you can instruct Flash to show only the outlines of the objects on a layer. The final button in each layer row in the Timeline is a square. Clicking on this square toggles the layer between normal view and outline view, allowing you to see the location of the object.

Layer Properties
Another way to work with layers is through the Layer Properties dialog box, which provides many options for customization in one place. To open the Layer Properties dialog box, either select Layer from the Modify menu or rightclick on a layer in the Timeline list and choose Properties. From this dialog box, you can change these elements:

Organizing Layers
As previously discussed in this chapter, the number of layers used in a Flash movie can start to add up. The simplest way to organize layers is to group together in a folder several layers that are similar or that have a common theme.

In addition to grouping layers together using folders, you can adjust the order of the layers in the Timeline. Do this by clicking and dragging any layer name to a new location in the list. Sometimes, organizing layers together without folders is sufficient.

Chapter 5. Symbols and Libraries


Symbols are reusable objects that can be used to quickly build animations and movies. In this chapter, you will learn the answers to these questions:

What is a symbol? What are the types of symbols? How can you create symbols? How can you edit symbols and instances? What is the library? How do you work with a shared library?

What Is a Symbol?
A symbol is a graphic object (in the simplest sense of the word, not in the programming sense) created for use in your Flash movie. More specifically, a symbol in Flash is a graphic, button, or movie clip. Consider the many Web sites you've recently browsed. These sites are composed, in part, of graphic objects. Sometimes these graphic objects are static, and at other times they have added behaviorsthey do something when you mouse over them or click on them. A symbol can be any type of these objects.

Symbols greatly benefit your Flash development. You can create symbols from scratch directly in Flash. Flash also allows existing graphics to be imported and converted to symbols. After a symbol is created, it is stored in the Library. Imported graphics converted to symbols are also stored in the Library. Flash has a feature that allows you to import graphics directly to the Library, as well. You can reuse symbols as an instance in any location within your Flash movie. If you edit a symbol, the changes you make affect every instance of the symbol in your movie. You have to make the change in only one place. Also, you can edit instances in their separate locations without affecting the original symbol. I will discuss instances of symbols and libraries later in this chapter. File size and playback speed are always important considerations with Flash movies. Symbols reduce the size and increase the playback speed of your movie. By using instances, the symbol you created is downloaded to the Flash player only once. For these reasons and others you discover throughout this chapter, the use of symbols is essential to becoming an expert in Flash. As I mentioned, Flash uses three basic types of symbols. Each type has different capabilities.

Graphics Buttons Movie clips

A few examples of objects that might be created as symbols include the following:

Company logos, frequently used in many locations Commonly used graphical buttons, such as menu navigation buttons Background animations that loop Any object that will be used multiple times in a movie

Let's take a closer look at each type of symbol.

Graphics

Graphic symbols have no interactivity associated with them, regardless of the user's input. These types of symbols are static images and are appropriate for only that type of use. You may use any of the tools in the Toolbox or on the menu to create graphics.

Buttons

When you think about pointing and clicking on something other than on a text link (a sentence saying "Click here," for example), that object is usually a button. If you complete a form on the Web and click on the word Submit, you are clicking on the Submit button. Buttons have states that respond to the actions of the mouse. A button can have a different state (or look different) when you mouse over it, click on it, or release it. After you have created the look of the

button's various states, you can then assign actions to them. For example, you can add an action that changes a button's background color to add emphasis when it is moused over.

Movie Clips

Movie clips are mini movies. I recommend creating symbols as movie clips unless you are absolutely certain that a symbol will never be animated. Animation is mentioned in this chapter, but it is covered more comprehensively in Chapters 6, 7, and 8. Each movie clip contains its own Timeline, complete with layers and frames. The Timeline of a movie clip, nested within the greater Timeline of the movie, plays when the layer containing the movie clip plays, independently of the main movie. This feature assists you in creating more complex animation. Here is an example. Suppose that you want to create a movie that involves the planets revolving around the sun. You first create symbols for the planets and the sun. Next, you animate the planets to move around the sun. These steps are created in the main Timeline. Later, you consider the option of having the Earth rotate as it revolves around the sun. But how would you make the Earth rotate separately from the other symbols in your movie? Because the Earth is a movie clip with its own timeline, you simply add the rotation to the Earth's Timeline. Your completed Flash movie will show the Earth rotating as it revolves around the sun. You will create this movie as you progress. NOTE New to Flash MX, movie clips now contain all the functionality of buttons, enabling you to add behaviors to the different states, as you would with buttons.

Creating Symbols
As you have probably noticed, Flash provides multiple methods for performing commands. As you continue, I will point out various options for performing these commands. There is no right way to perform an action. It is truly a matter of personal preference, so feel free to use the method most comfortable for you. To create a new symbol in Flash, select Insert, New Symbol or press Ctrl+F8 ( +F8 on a Mac).

Naming Symbols

NOTE A new feature in Flash MX is a coding assistance process used in ActionScript. Although you may think that using ActionScript is a little advanced, this book will provide you with a basic introduction. If you follow the Flash MX naming convention, the code editor provides all your options for that particular object based on its name. That may sound a bit confusing, so let me clarify: Button names should end with _btn; for example, SubmitButton_btn. Movie clips should end with _mc; for example, Earth_mc. Text files, which come into use with ActionScript, should end with _txt; for example, MylistofNames_txt.

Based on the ending letters of the symbol's name (_btn, _mc, or _txt), ActionScript provides a list of available programming options. Although you may or may not be using ActionScript right away, you should use these naming conventions. Using them also assists you in identifying your symbols. Click the Advanced tab to display this menu.

Creating Symbols
Now that you understand some of the important concepts behind symbols and why they should be named as such, let's create them. You will create a movie clip and a button. Creating a Movie Clip Now create a movie clip to use in your first Flash movie. You are creating a movie clip so that animation can be added to it. This movie clip will be the planet Earth. Start by creating a new symbol.

Follow these steps to select the color of the symbol.

Now use the drawing tools found in the toolbox to draw the symbol.

Now give the Earth some dimension by using the gradient tools.

At this point, you've chosen a color for your symbol, edited that color, and added a radial gradient to it. With the finalized color selection, you have drawn a circle.

Creating a Button Buttons can add functionality to a Flash movie. They can be used for navigation, changing the screen as in a rollover, or submitting information. Now create a simple button to use in your movie. Start by adding a layer to the timeline for your button.

NOTE Remember, layers are ordered from the bottom up, so new layers are always on top of the current layer you are working on.

Next, create a new symbol.

Again, you are in symbol editing mode. The name of the button is in bold above the Stage. The Timeline is specific to learnMore_btn, not to the Timeline of the main movie. Also, four frames represent the states of the button in the Timeline.

Begin work on your button in the Up frame. This state determines your buttons appearance at rest (when it's not being moused over). 1. Select a fill color (any dark color will work). 2. If you want, select a stroke color also. 3. Click the Rectangle tool in the Toolbox. Next, follow the steps below to draw the shape of your button.

1. Place your mouse pointer over the Stage. 2. Click the mouse and drag it over the Stage. When the rectangle is the desired size, release the mouse button. 3. Select the Text tool from the Toolbox. Often, buttons directly state their function with text.

Your text should be in a color that shows up well on your rectangle and a size that fits within its borders. You may need to edit your text settings.

Make sure the text is properly aligned within the rectangle.

The Over state determines how the button will look when moused "over." You want to create an easily discernible difference so viewers know the button does something. Follow these steps to prepare the Over state frame and change the background color.

Edit the button so that its behavior changes whenever you mouse over it. To change the background color, follow these steps.

Now the color of your button changes when moused over.

Converting Existing Graphics to Symbols


There will likely be times when you want to use a piece of artwork already created outside of Flash. Flash allows you to import that artwork easily and give it the functionality of a symbol. Flash provides many methods for the conversion process, allowing you to also convert graphics created in Flash to symbols, as well as groups of graphics on the stage. Importing Existing Graphics As mentioned, you can import existing graphics into your movies and convert the graphics to symbols. When you consider the role of Flash movies on the Web, however, large files do not make sense. Although the option of importing sophisticated graphics may be useful, you should not overuse it. Whenever possible, you should create images directly in Flash because the file sizes are likely to be significantly smaller. Complete the following steps to import a graphic:

Your graphic has now been imported to the library. Converting Imported Graphics to Symbols Follow the steps below to convert imported graphics to symbols. It is very simple, 1. Click your graphic once to select it. 2. Right-click it and select Convert to Symbol. Converting Graphics on the Stage to Symbols Flash MX also provides the option of converting existing images on the Stage to symbols. This feature can be helpful if you miss the initial step of inserting a new symbol. This process is also useful if you want to group several items on the Stage into one symbol. In this section, you create paths for the solar system and convert them to one symbol. First, prepare the Stage by hiding the layers not in use.

Next, choose the appropriate color selections.

Begin drawing the path by following the steps below.

After creating three separate graphics, combine them into one and convert it to a symbol.

The steps involved in converting a graphic to a symbol are similar to those you followed when creating a new symbol.

Editing Symbols and Instances


As mentioned, symbols can be used in various places. When you drag a symbol from the Library and place it on the Stage, you have created an instance of that symbol. Each separate use of the symbol is an instance. The use of instances helps to reduce the file size of your movie. Flash downloads the entire symbol only once and uses smaller bits of information for each instance. Furthermore, after you edit a symbol, all instances of that symbol reflect the change, so you have to make changes only once. You can edit instances of the symbol without affecting other instances or the original symbol. If you want to customize the name of your instance, you need to do so in the Properties panel. You can edit symbols in many ways. By selecting an instance of a symbol on the Stage and right-clicking it, you will see three Edit menu items:

Edit Edit in Place Edit in New Window Edit. Displays an editing window in place of the Stage. You are in symbol-editing mode and can make changes directly to the symbol in this window.

Edit in Place. Enables you to edit the symbol directly on the Stage among the other objects on the stage. You have visibility of the full Stage. Other items on the Stage are shaded until you return to the main scene and the Timeline.

Edit in New Window. Creates a new editing window in addition to the Stage. You may need to shrink your editing window slightly to view both displays at one time, but you can alternate between the main movie stage and the stage of your symbol.

If you have more than one scene, the scenes are listed on the Edit Scene button's shortcut menu. The Symbol icon displays all the symbols contained in the Library.

After you have edited your symbol, you need to return to the Stage. You can do this by following one of these methods:

NOTE Navigating between the main Timeline and symbol-editing mode can be confusing because the Timeline changes. Be sure that you know which timeline you are affecting before you make changes or additions. To edit a symbol, click the Edit Symbol button and select earth_mc. You are now looking at Earth in symbol editing mode.

Follow the steps below to make changes to Earth:

What Is a Library?
The Library serves primarily to store all your symbols and let you check out instances of them. It can also store objects that are not symbols, such as sound or video. Essentially, the Library allows you to view all your assets at a glance. Everything contained in your movie should also reside in the Library.

You can create folders in the Library to organize your work just as you would create folders on your computer. Three folders are in the Library: Planets, Stars (a subfolder of Planets), and Buttons. Double-click on a folder to display its contents. Note the following parts of the library:

You may also copy or share library assets between movies to add an additional layer of reusability. You can do this by opening both libraries and dragging items from one library to the other.

Working with a Shared Library


Using a shared library enables you to use items from one library in several different movies, cutting down on development time and improving efficiency. You can share items from the Library in two ways: runtime and author-time sharing. If you have dabbled in Web page development, you know that you can assign relative or absolute URLs to links. A relative link looks something like \servername\foldername\filename; an absolute link looks like http://www.fast&easy.com. The same principle applies to runtime and author-time sharing.

Runtime Sharing
As you might recall, whenever you click Advanced on the Create New Symbol window, you see check boxes that allow you to import or export runtime sharing. In runtime sharing, the item has an absolute location and can be accessed outside the local network. If you are working on a project with a remote team member in Alaska, for example, you can still share libraries.

Author-time Sharing
Author-time sharing involves sharing an item across a local network. Author-time items can be shared in an office building among an internal team, for example. When you are sharing assets, note that Flash has a feature that resolves library conflicts. If a library item is being copied to a Flash file that already has an item designated by that name, you can choose whether you want to replace the current item with the new item. Flash does provide the option of creating a permanent library for the images used in your movie. To make a permanent library, place the Flash file in the Libraries folder in the Flash's application folder on your hard drive. You can get to this area by double-clicking My Computer from the Desktop, double-clicking your C drive, followed by Program Files, Macromedia, Flash MX, First Run, Libraries.

Part II: Animation


This section introduces the fundamental concept of animation. Background information and a historical perspective provide you with a solid foundation. You will learn the difference between motion tweening and shape tweening as well as how and when to apply both. You will see that masking allows you to create interesting effects in your animation.

Chapter 6. Animation Basics


To this point, I have discussed Flash movies and animations without truly explaining what they are. This chapter remedies that situation by answering these questions:

What is an animation? What is a frame? How do you create simple frame-by-frame animations?

What Is an Animation?
The simplest definition of an animation is a series of pictures that are rapidly shown in sequence. All the cartoons and movies you watch in a theater are thousands and thousands of pictures that are shown for a fraction of a second each. The human eye can handle only so much input at a time, and it holds an afterimage for the fraction of a second that it takes to switch from one picture to the next. When pictures are shown quickly enough, with small differences between them, movement is created. Using this concept, simple movies have been in existence since the late 1800s. Animation was, before the advent of computers, a tedious process involving large numbers of cartoonists and artists. A picture, or animation cell, was created, and then a second cell, almost identical to the first, was created. The differences between the two cells were subtle. Another cell was drawn and then another and another. Because most animated cartoons and movies are shown at a rate of 12 to 45 pictures per second (if not faster), a single half-hour cartoon contained at least 21,600 separate pictures. The completed cells were transferred to film, the film was then placed in a projector, and the tireless efforts of the animation staff were finally shown on the screen. Thankfully, computers and software have simplified this process a great deal. Flash MX helps with the creation of movies in a number of ways. However, to fully appreciate the tools Flash contains, you should create a movie the "oldfashioned" way first

What Is a Frame?
You can think of a frame as an individual picture, or animation cell. In Flash, frames can be treated almost like their realworld counterparts. All the pieces of your movies reside in frames. Flash has two types of frames: keyframes and frames. Keyframes are special frames that Flash uses as markers in an animation. Keyframes can indicate changes in the animation, and they hold most of the items in an animation. Frames, which fill the areas between keyframes, are either identical to the keyframe that precedes them in the Timeline or are used by the built-in animation tools. Different frames are represented in the Timeline by unique characteristics.

All frames represented in the Timeline have a number of properties.

How Do You Create Simple Frame-By-Frame Animations?


Simple animations, created frame by frame, are a great way to start. They can help familiarize you with the tools that Flash has, and also show the tedious nature of old-fashioned animation. This comparison allows you to appreciate some of the tools in Flash much more than you would if I presented them first.

The Basic Steps

NOTE When you choose Insert Keyframe, the contents of the last keyframe are automatically copied into the new keyframe. When you choose Insert Blank Keyframe, none of the contents of the preceding keyframe is copied.

NOTE When you press the Enter key, Flash plays the movie from the selected frame to the end. If you are on the last frame, Flash plays the movie from the beginning. Pressing Enter again, while the movie is playing, stops the movie at the current frame.

Create a Simple Movie with Motion Tweening


Creating a movie frame by frame with one layer is simple but time-consuming. However, a movie like the one you just created is relatively boring. To create a movie with three different elements, you need the following:

A background Text that moves from right to left An object that moves from left to right

Create a Background First, you need to create the background to provide some foundation to your movie.

NOTE Save early; save often. Whenever you want to do something major to your movie, save it first. Use several different file names. This way, you can always go back to a workable movie, even if you make a major mistake. With the long file name support in most newer operating systems, you can create descriptive file names, like "MyMovie_JustFinishedBkgd.fla" Add Moving Text You are done with the background for a moment. I know that it has a duration of only one frame, but will I show you how to fix that problem in a bit. Now, you need to add the moving text.

NOTE The simplest way to move an object is to select it with either the Arrow tool or the Subselection tool and then use the arrow keys on the keyboard. Each keypress with the arrow keys moves the selected object in the desired direction a little bit. To move the object more than a little bit, hold the Shift key and press an arrow key.

NOTE The farther an object moves between two frames, the faster it seems to move in the movie. Use the Onion Skin Tool Now you have completed two of three parts of your movie. Let's take a moment to use one of the other tools in the Timeline: the Onion Skin tool.

Add a Moving Object

Next, you will add more motion to your movie with the addition of a moving object. You will create objects that begin in one area of the stage and move to another. There are many ways objects can move or change. The different ways are addressed in Chapter 7, "Animation with Motion Tweening" and Chapter 8, "Animation with Shape Tweening."

NOTE It may seem odd to delete all the frames that Flash added to the new layer for you. Unfortunately, in this case, deleting the frames and replacing them with keyframes is simpler. By adding keyframes one by one, after moving the object in the

preceding keyframe, Flash does a bit of extra work for you, by copying the contents of the preceding keyframe. This action saves a great deal of work using copy and paste. All this work has created a very rough movie. To preview it, follow these steps:

Troubleshooting Now, if you followed all of the steps in this section it is likely that you have two problems:

The background is visible for only a short time at the beginning of the movie. Either the text or the moving object disappears before the end of the movie.

Thankfully, both these problems are easy to solve. In fact, they are the same problem. A number of frames exist in one layer, but not in the others. So, you need to fill in the rest of the frames for the layers that finish too quickly. To fix the background first, follow these steps:

The background should remain visible during the entire movie.

NOTE It is usually obvious that one layer finishes before another when you look at the Timeline. You can see pretty easily the last frame used in each layer. However, sometimes you want one layer to finish before another, for example, if an object

is supposed to move off the Stage and not be seen again in the movie. In this case, the last frame in the layer with the moving object might finish well before the last frame of the movie. Unless both the moving text and the moving object were completed on the same frame number, one of the other layers still disappears before the end. If so, you can skip the steps below, otherwise, you need to do the following:

The movie should look a little more polished than before. To finish working on the movie, run through the following checklist and fix any problems that might exist.

Does the animation run smoothly? Does anything look bad? Do you see anything that does not belong? Are the colors too loud or too soft? Is everything you want seen on the Stage in the work area? Does the movie convey the ideas you want?

Chapter 7. Animation with Motion Tweening


So far, I have covered the different tools available in Flash and how to create a movie the hard way. Now, you will learn how to create a movie the easy way. In this chapter, you will learn the answers to these questions:

What is motion tweening? What can you do with tweening? Does tweening work with color? How do you use motion guides with tweening?

Motion Tweening
Motion tweening is a tool Flash gives you to easily create animations. Tweening is short for "in between." Basically, you can create a keyframe with an object, create another keyframe on the same layer with the same object in a different location, and Flash will supply the frames in between the two keyframes. Rather than defining the look for objects per frame, Motion tweening allows you to identify the keyframe of change and let Flash do the rest. Try it out.

The Basic Steps

Creating a Simple Movie with Motion Tweening


Using tweening is much simpler than drawing every single frame. To do something a little more complex, you can create a movie with three moving objects that start and stop at different times. Here's a list of what this movie will contain:

A background. The first object moves from off the left edge of the Stage to the lower-right corner. This process happens from Frames 5 to 25. The second object moves from off the right edge of the Stage to the lower-left corner. Frames 20 through 45 contain this object. The third object, some text, moves from off the bottom of the Stage to center itself on the Stage. Frames 15 through 50 contain the moving text.

Create a Background Begin by creating the background.

NOTE Get into the habit of locking layers when you are finished with them, to prevent accidentally changing part of a layer that is complete.

Add Objects The background is complete. Now add the first object in frames 5 to 25 by following these steps:

NOTE When you use motion tweening, every moving item should be on its own layer. If you have more than one moving object on a layer, Flash can get confused when you create the tween. The second object moves from right to left from Frame 20 to Frame 45. The procedure is similar to what you have already done.

The moving text moves from the bottom to the top from Frames 15 to 50.

You should pat yourself on the back because, in just a few minutes, you have created a movie with several moving objects.

Tweening Effects
By this time, you have probably noticed that the Properties panel has a few more items in it when you select a frame that is part of a tween, compared to a regular frame or keyframe. These new properties are:

Resizing an Object in a Motion Tween


Let's work with a few of these new properties. Start by resizing an object in a motion tween.

To skew an object as part of a tween, follow the preceding steps; in Step 8, however, use the Free Transform tool to skew the object, not resize it. Or, you can do both. NOTE In this example, you created the tween and then changed the last frame. This technique works for moving, scaling, rotating, and skewing.

Rotating an Object with a Motion Tween


Rotating objects with a motion tween works similarly to the process of resizing objects just discussed.

So far, these tweens have been simple because you changed only one thing at a time. Let me introduce a new panel, the Transform panel, and see what you can do with it and tweens. The Transform panel is accessed by choosing Window, Transform or pressing Ctrl+T ( +T on the Mac). This panel contains eight items:

For practice, now apply the above steps to the earth symbols created in Chapter 5, adding rotation to the earth.

Transforming an Object with a Motion Tween


Now let's play with the Transform panel and tweens. You will create two objects. The first object expands and rotates, and the second one shrinks and gets skewed.

Tweening with Color


Colors are another option you can change in a motion tween. You can change a few different attributes with colors and motion tweens, including the following:

Brightness Tint Alpha Any or all of these options, via the Custom option

NOTE One concept you should understand about changing colors in motion tweens is that the process is somewhat limited, since motion tweens can deal with only symbols and instances. In fact, if you create a motion tween using objects that are not symbols, Flash creates a symbol in the library for you, and from that point you are editing only instances of that symbol.

The Basic Steps


You can change all these characteristics via the Properties panel. Start by changing the brightness of an object.

Using Color Tweening in a Simple Movie


Change the tint next. Rather than create a new movie, you can simply edit the one you just finished.

NOTE Did you notice that when you change the tint, brightness reverts to its original settings? Changing more than one option is possible only by using the Advanced setting, which I will cover shortly.

The alpha setting is not only fun to play with, but also useful. Think of the alpha setting as how strongly the object is visible. For example, 100 percent alpha is completely there, while 0 percent alpha is completely invisible or transparent. By using alpha settings, you can make objects fade in and out, which can be great for pop-up menus, special effects, and transitions.

Advanced Features
Now create a new movie in which an object fades in and then fades out. It fades in from Frames 1 through 15, stays solid until Frame 30, and then disappears by Frame 45.

The other color tween you can work with is the Advanced tween. Using the advanced options, you can change both the tint and alpha settings. However, the advanced settings are a little bit tricky and require that you understand RGB colors. Colors can be represented by three numbersone for each color: red, green, and blue. All colors, as far as computers are concerned, can be created by mixing these three colors. RGB values are a combination of three numbers, and each number is between 0 and 255. The first number represents how much red is in the color; the second, how much green; and the last, how much blue. Black is represented by (00,00,00), white is represented by (255,255,255), and gray is (128,128,128). The Advanced Colors Tween settings, which assume that you know about RGB colors, allow you to change the color and alpha settings by using a simple formula. For each setting (red, green, blue, and alpha), you can fill in two values: a percentage of the original value to use and an amount to add to thator, more simply: The new value = (the original value * percentage) + new number (0 255) This formula should become a bit clearer after you see it in action. Let's try working with these advanced settings.

Although there are limits to what you can do with color tweening, it is still an important and useful tool in Flash.

Motion Guides
With motion guides, animation can get interesting. Objects in a tween do not necessarily need to move in a straight line, as in all the previous examples of this chapter. Instead, you can create a path for the object to follow during the tween. This process is simple, as you will see. NOTE For the examples in this section, only one object is usedan arrow that points upso that you can see how orientation can change in a few circumstances.

The Basic Steps


The following instructions introduce you to the concept of motion guides and how they work.

The Orient to Path option is a little difficult to explain. The best way to explain it is to show a frame from a movie without the option turned on and then show the same frame with the option enabled.

Applying What You've Learned


Now, you can pull together all the different motion tweens and create an animation in which one object moves along a motion guide, changes colors, rotates, and fades out. For simplicity, you work with only one object, and it does everything at once in a four-second movie.

Chapter 8. Animation with Shape Tweening


Thus far, this book has covered how to create animations by drawing every single frame and by using motion tweening. However, sometimes these techniques do not work effectively to create complex animations. Shape tweening offers animation with a different look. Whereas motion tweening generally takes an object from one location to another and allows for some changes to the shape (such as height, width, or x and y position), shape tweening allows an object to become something completely different. For example, a circle gradually morphing into a triangle illustrates the concept of shape tweening. In this chapter, you will learn the answers to these questions:

What is shape tweening? How can you use text in shape tweens? How do shape tweens work with color and other properties? What are shape hints, and how do you use them?

What Is Shape Tweening?


Shape tweening is similar to motion tweening. In motion tweening, you create an object and tell Flash where to move the object, and Flash handles the rest. With shape tweening, you create the object as you want it and then create a new object, and you let Flash fill in the work in between the two. As previously mentioned, shape tweening, which involves changing one shape into another, can be as simple as a circle becoming a square or as complex as a row of boxes becoming letters in a word. Basically, any shape or object can become another. NOTE Shape tweens are often referred to as morphs, so don't let the interchangeable terminology confuse you.

The Basic Steps


Let's begin with the simple task of having a square become a circle. You can do this in several ways, but the simplest is shown in these steps.

NOTE Flash MX provides feedback to indicate when problems occur with tweens. In the Timeline, an incomplete tween appears as a dashed line. A complete tween appears as an elongated arrow between keyframes. You can have an incomplete tween preceded and followed by complete tweens or vice versa. When problems do appear, look at both the first and last keyframes in the incomplete tween to try to discover the problem. In some instances, Flash also displays a warning icon to the right of the Ease drop-down list in the Properties panel. Clicking on this icon reveals a message that can be very helpful in troubleshooting. NOTE Just as with motion tweening, Flash behaves much better when each animated object is on its own layer. Otherwise, Flash may confuse the other objects on the layer as part of the shape that is being tweened. This situation can result in odd behavior.

Working with Complex Shapes


Pay attention to one caveat in shape tweening: It works with only simple items. Complex shapes, objects, imported graphics, and text must be simplified into pieces for shape tweening to work properly. To convert an object to its component parts, select Modify, Break Apart or press the shortcut Ctrl+B (+B for the Mac). Here is an example of how to use an imported graphic in a shape tween.

NOTE When taking a graphic through the Break Apart process, the desired result is for the graphic to be converted to a fill. Depending on the graphic, this can take a few tries. For example, when working with a complex graphic, I needed to press Ctrl+B ( +B for the Mac) three times before the graphic became a fill. If you have forgotten how Flash denotes a fill, draw a square and click on it once with the Arrow tool. The many dots covering the square indicate the fill. Your graphic should look like this after the Break Apart process.

In this example, you may notice that the fill changes at the last instant while the shape changes and moves gradually. This is one of the limitations of using preformed graphics files in a shape tween.

Text Effects with Shape Tweening


Working with text in a shape tween is a little more complex than changing a square into a circle. The reason is that you must break apart text twice. The first time separates the single text block into many blocks, one for each layer. The second time you break up text, each of the letters becomes a fill that looks just like the text character, but is, in fact, just a graphic.

The Basic Steps


In this simple example, five rectangles become the word Flash.

NOTE I have noticed a possible problem with Flash and shape tweens. Sometimes, when you fix an incomplete tween (as indicated by a dashed line in the Timeline) by adding the last piece needed, the dashed line does not become an arrow to tell you that everything should work. When you think the shape tween is complete, click on a different frame in the Timeline, and Flash should be forced to update the display. Or try playing the movie and see if all items display properly.

Working with Complex Text


That simple example shows how to create a morph of shapes into letters. How about morphing one word into another and then morphing the second word into a third? An example is the opening credits for your Flash movie, with a name like Premier Press changing to presents, which then changes to Flash MX. Another example is part of a movie describing your company, where, as the movie progresses, the captions or headings change with the topic of the movie. For example, the first part of the movie might be a background about the company with the heading Our Company History at the top. Then the text could morph into the words Our Company Today as the content changes and then change to Where We Are Headed when the company's future is discussed. NOTE Morphs and shape tweens are often subtle, not abrupt, changes that blend into the rest of the movie. If the changes are too abrupt or complex, they can take attention away from the content or subject matter that the movie is trying to convey. Try creating a simple example:

NOTE When you are creating shape tweens with text, the text can be in different fonts, colors, and sizes. Just change these properties before you break the text apart. After you have selected Break Apart on the letters to change them into graphics that Flash can use in the tween, you cannot change the font, and changing the size is difficult. For interesting effects, vary the location, size, colors, and fonts to see what sort of neat transitions you can create.

Working with Shape Hints


So far in this chapter, I have covered simple shape tweens and text tweens. However, sometimes things are too complex for Flash's built-in tweening tools. In this simple example, you will create a rectangle that becomes an oval. Then you will identify and fix the problems that occur. In a new Flash file, follow these steps:

Notice that when you play the movie, the rectangle rotates as it becomes the oval. The tweening tool thinks that this event should happen, but it just doesn't look right. What can you do to stop the rotation? The wonderful people at Macromedia anticipated problems like this one. They even added a feature that can mitigate problems with shape tweens: You can add hints to keyframes to show that a specific point on the shape in the first keyframe will become a specific point in the last keyframe. For example, to stop the rotation of the rectangle into the square, you can place a hint in the middle of the topside of the rectangle in the first frame and place a hint at the top point of the oval in the last keyframe. Continue working with the file you began work on, and follow these steps:

NOTE Hints are a great tool. There are, however, a few important things to remember:

Hints apply to a single tween from one keyframe to the next. Hints can be placed only in keyframes. Red hints are not attached to a shape. Yellow hints are hints attached to a shape in the first keyframe of a tween. Green hints are attached to a point in the last frame of a tween. Hints are labeled with letters. The first hint added is a, the second is b, and so on. Hints are paired. Hint A in the first keyframe moves to Hint A in the last keyframe. In the next tween, Hint B in the first keyframe moves to Hint B in the last keyframe.

When watching the movie, you probably noticed that the point that was marked in the first keyframe moved to where the hint in the last frame was. This move didn't stop the rotation, but it did minimize it. Fix the rotation completely by adding one more hint.

The rotation should be stopped, and the rectangle should just expand (or contract) into an oval. Now see what happens when you change things a bit by moving Hint A from the top to the bottom in the last frame.

Notice that this simple change has an odd effect. As the movie plays, the shape flips over into itself as Hint A moves from the top to the bottom. This effect can be the result of the unintentional placement of hints. If desired, however, it looks neat. NOTE As with most tasks in Flash, you should approach hints cautiously. Add only one hint at a time, testing as you go, to make sure the objects behave as you think they should. Also, save your work before you make a major change so that you can revert to an older version of your movie if necessary. Now you should either move Hint A back to its position at the top of the oval or delete it. To delete a hint, follow these steps.

NOTE One menu option is labeled Remove All Hints. This feature, which worked intermittently as I wrote this chapter, may not be an official bug, but if it does not work properly, you can still delete each hint separately. It works best if you select this option from the first keyframe using hints.

Chapter 9. Masking
Masking is a flexible tool in Flash. With masking, a number of neat effects are possible. If Flash is like theater on the web, consider masking high drama. You can affect visibility in ways that create surprising looks, particularly when applying tweening options to a mask. In this chapter, you will learn the answer to the following questions:

What is a mask? How do you create a simple mask? How do you use movie clip symbols in masks?

What Is a Mask?
A mask is a window through which you can view the Stage. One of the simplest ways to think of a mask is shown in the following example. Hold up to one eye an empty paper towel roll (the cardboard cylinder that is left when all the towels are gone) and close your other eye. You can now see the small portion of the world that is visible through the end of the tube. This tube is a simple mask. It hides everything except what is visible through it. In Flash, you can create masks that serve a similar purpose, to hide any extraneous objects or parts of the Stage.

How Can You Create a Mask?


Creating a mask takes a little bit of planning. You need to decide what you want hidden, what you want visible, and how the area of visibility should look in terms of shape and size. A common use of a mask is to hide part of a graphic that has been imported into Flash. Another example is a spotlight that moves around the animation, showing a small portion of it at a time.

The Basic Steps


After you have made these decisions try your hand at creating a mask by following these simple steps.

You should now have a "window" through which you can view part of the graphic you imported. You should notice a few things about the mask you just created.

The mask you created is simple. It is one frame long, and its layers are locked so that you cannot edit them. From this example, however, the general idea is illustrated.

Creating a Moving Mask over Static Content


There are many ways to work with masks. Now add animation to the mask through which the static picture will be visible.

NOTE Masks work only when the masked layer and the masking layer are locked. So you must remember that if you unlock either layer to edit it, you need to lock it again so that the mask displays properly.

Creating a Static Mask over Moving Content


Now let's try a different approach by adding movement to the content beneath the static mask.

NOTE One drawback to using masks is that a mask layer cannot have a motion guide associated with it, so you cannot easily create an animated mask that follows a preset path. The easiest way to work around this limitation is to break up the animation into several different tweens, each with simple movement from one point to another.

Create a Mask That Moves over Animation


Now mask a second layer using the same mask as in the preceding movie.

Create an Animated Mask That Moves over Animation


Now make things really interesting by having an animated mask moving over an animated picture. For the animated picture, you use a shape tween.

Using Movie Clip Symbols in Masks


Now use a symbol for the animation and a moving oval as the mask.

You can create lots of neat and sophisticated effects by using the masks you have explored in this chapter. With a little creativity, you should be able to apply these concepts and create amazing movies.

Part III: Sound


Sound is an interesting entity all on its own. This section provides background information about what sound is and how you can use it in Flash. You will learn how to import sounds and attach them to your movies. This section also explains the limitations of working with sound on the Web, enabling you to make educated decisions when you're adding sound to your Flash movies.

Chapter 10. Sound


Used well, sound creates an additional dimension to your Flash movies. Sound can add warmth, feeling, or humor. Sound can also be distracting if overdone, however, so use it wisely. In this chapter, you will learn the answers to these questions:

What are the basics of sound? What are the different types of sounds? How do you import sounds? How do you add sounds to the Timeline? How do you work with sound and buttons? How do you modify and customize sounds? How are sounds compressed?

What Are the Basics of Sound?


Flash does not have the capacity to create sounds. You import sound files into Flash and then edit the files from there. If you want to create sound files, basic software programs are available that need only a sound source and a microphone. This process is relatively simple, albeit unsophisticated. For purposes of this chapter, existing sound files are imported into Flash. The goal is to achieve the best possible balance between sound quality and file size. Sound is the largest contributor to the size of an exported Flash movie. A sound file that is too large can prevent a movie from being displayed in the browser. When digital sound is adapted from its analog form, it must be sampled. Sampling involves taking multiple snapshots, or samples, of a sound wave for a given amount of time. After several snapshots are collected, they are reassembled as a replication of the original sound. This process digitizes the sound. A higher number of snapshots results in better-quality sound.

The Different Types of Sound


Flash supports several file formats for importing sounds. Some sound formats are platform specific, and others have some compression applied to the original sound.

MP3 (Motion Picture Experts Group, level 3). The standard file type for sound on the Internet. Critics of this file type feel that quality can be sacrificed because MP3s have usually undergone some level of compression; however, you are still able to customize the resulting output. WAVE. The native Windows sound file type. Wave files are typically not as efficient as MP3s, even after compression. AIFF (Audio Interchange File Format). Developed by Apple Computer; the format of a great deal of professional music. QuickTime 4 or higher enables an AIFF file to be imported on a Windows machine.

AU. The file type commonly used when sounds are made on a Unix computer. These files have typically undergone heavy compression and may not be the best choice for use on the Web. QuickTime. Enables compatibility with any file type. You can download it for free at http://www.apple.com/quicktime/download/.

Many sound files on the Web are produced in mono rather than stereo (meaning they are designed for just one channel instead than two), which is okay for use in Flash. Both speakers are activated by a mono filethey are simply playing the same sound, contrary to suspicions that only one speaker plays.

Importing Sounds
Imported sounds work much like symbols. Sounds are imported into the Library and can be used in a shared library. They are not automatically placed on the Stage, however.

Adding Sound to the Timeline


In this chapter, you gain a sense of how to add sound to the Timeline manually. ActionScript allows you to dynamically add sound to a movie.

You can think about sound in a Flash movie in two primary ways: streaming sound and sound events. Sound must be added to keyframes in the timeline regardless of the approach.

Streaming Sound
When sound is streamed, it is given an exact starting point on the Timeline and, often, an exact stopping point. After the initial keyframe, you may need to add frames to allow for the expanse of the sound file. Sewing is a helpful analogy: Think of streaming as stitching the sound file to the animation timeline. This process has both benefits and limitations. Streaming does allow precise control over when the sound file begins to playtheoretically. Playback begins when just a few seconds of the sound file have been downloaded. If the sound file plays more quickly than the download, gaps occur. Also, sound takes precedence during downloading. The Flash Player tries to continue playing the sound file smoothly at the expense of the animation. If problems occur, the Flash Player drops frames in an attempt to keep up, the results of which can be a choppy movie. If the sound is called to play again, the download process starts over because the sound is not stored in the computer's memory.

Using a Sound Event


Sound used in the form of an event has more stand-alone properties than streaming sound. A sound event is inserted into a keyframe, but is not attached to the Timeline in the same manner as streaming sound is. A sound event is given a starting point in the movie, but from there it acts independently. For example, the sound continues to play in its entirety even if the movie has finished playing. A sound event works much like a symbol. The sound is downloaded completely before beginning to play; however, the sound is downloaded only once and can be reused without greatly increasing its file size. Downloading the entire sound can affect the load time for the movie. Also, without being instructed otherwise, the sound can overlap. If a sound event is attached to a button, for example, and the user clicks the button five times in quick succession, five versions of the sound begin to play, and they play in their entirety. You can imagine what this situation might sound like. Consider the following general approaches to the use of sound. If the sound is short and you are using it more than once (in a loop, for example), you should create a sound event. Good examples of event sounds are button noises that occur when you click a mouse button. Preloading event sounds is a good idea. Consider streaming sound if the sound plays for a longer amount of time, if you need more precise control over its playtime, if you need for it to start at the beginning of the movie, or if it plays only once. Try adding sound to the Timeline.

The Sync drop-down list on the Properties Inspector contains Event, Start, Stop, and Stream options. Event and Stream refer to the sound event and streaming sound discussed earlier in this chapter.

The Start option is similar to the Event option in that the sound runs separately from the Timeline. Unlike the Event option, the Start option does not allow more than one instance of a sound to play until the preceding instance of the sound has finished playing completely. This feature is useful for a longer sound that takes a while to play because it prevents the sound from overlapping itself. The Stop option is self-explanatory. You can attach the stop option to a keyframe to make the sound stop. This action stops only one sound file, however. If you want all sounds to stop, use the ActionScript command stopAllSounds. Loop is located to the right of the Sync option. You can set your sound to loop as many as 999 times, which should be plenty. If you want your sound to continually loop, you can put a higher number in this box. Although you do not see additional copies of your sound file appear in the Timeline when you add a loop, you see them in the Edit Envelope, where you can customize the whole sound or each individual loop.

Working with Sound and Buttons


Flash allows sound to be added to a button directly in its own Timeline. Choose short sounds, appropriate for "clicks," to add to buttons.

You can add sound to each state of the button and use different sounds. Each state needs a new keyframe to which sound can be added. You apply effects to the sound file by using the Effect drop-down list in the Properties Inspector. Effect options are covered in-depth in the next section.

Modifying and Customizing Sound


Flash has some nice features for editing sounds. The settings created for each sound individually are exported with the sound file. If you edit sounds individually and then change settings in the Export dialog box, the local changes, when exported, take precedence over the global settings. Likewise, if the settings are only adjusted in the Export dialog box, those settings apply to all sounds universally, reducing your influence on the output.

Left Channel. This option plays the sound file only in the left channel. Right Channel. This option plays the sound file only in the right channel (as you might have guessed). Fade Left to Right. Sound begins playing in the left channel and gradually gets softer in the left channel as it gets louder in the right channel. The sound concludes with full volume in the right channel and silence in the left channel. Fade Right to Left. The same process occurs as in the preceding bullet, beginning in the right channel and ending in the left channel. Fade In. Play begins with no volume and gradually increases to full sound. Fade Out. Play begins at full volume and gradually increases to no volume. Custom. This option allows you to create edit points in the sound and change volume levels in the right and left channels.

You see an Edit button beside the Effect drop-down list. The button opens the Edit Envelope window. Let's take a closer look at the components of the Edit Envelope window.

Now that we've discussed the elements of the Edit Envelope and how they work, let's take a closer look at how to create custom effects.

Play around with these options and have some fun.

Compression
Undoubtedly, you have had the experience of making a pho-tocopy of a copy rather than of the original. The more steps away from the original, the poorer the quality of your results. The same philosophy applies to sound. If at all possible, you should begin with an original file of high quality that has not been compressed. Let Flash do the compression for you. Sound comprises the bulk of the exported file size, so you should not skip this process. A large sound file can have dramatically detrimental results on animation, particularly on older computers. Compression options can be set for event sounds individually, with these sounds retaining their settings. Streaming sounds, however, are all exported as a single file, applying the highest setting individually used to the group.

Flash exports sound according to the selections made on the Compression drop-down list. If the default settings are left alone, compression occurs according to the global settings in the Publish Settings dialog box (found on the File menu). Using global settings is okay if all the sounds in your movie should be exported according to the same specifications.

Default. As discussed, this selection applies the global settings created in the Publish Settings window to all sounds. ADPCM. ADPCM, or Adaptive Differential Pulse Code Modulation, is sometimes used as a method of speech compression. Use it for short sounds (like button clicks). It provides support for Flash 3.

The following list provides you with a guide to appropriate Kilohertz selections for sample rates.

5KHz. The lowest possible setting for recognizable speech. 11KHz. The lowest setting you should use for music; 25 percent of the standard rate for CDs. 22KHz. A common choice for Web playback; 50 percent of the standard CD rate. 44KHz. The standard audio rate for music CDs. MP3. A commonly used compression standard that tends to give the best sound for the file size. Leave the Quality option set to Fast. Anything higher than that can slow things down and get the sound and animation out of sync. Raw. As you might guess, the Raw option provides straight sound with no compression exports. Changing the Quality setting can have some effect on reducing the file size. The same sample rate rules apply as in ADPCM. This option is usually not practical because the file size is too big. Speech. This option is a good choice for voice tracks. Voice can be recorded at a lower frequency than music soundtracks (11KHz or lower usually sounds good).

The information at the bottom of the Sound Properties window shows the current size of the file and the percentage of the original size remaining after compression. Alter these settings, clicking the Test button on the right side after each change, until you have the best sound quality at a desirable file size.

Troubleshooting
As you have probably discovered by now, sound is not always a precise science. Differences in computers and connection speeds, file size, and compression methods, for example, can cause problems with your movies.

Cutting silence from your sound files helps reduce file size. Silence is exported as actual sound, so it can add to the size of your file. Get rid of whatever you do not need. If playback looks choppy, consider selecting Auto High from the Quality drop-down list on the HTML tab in the Publish Settings dialog box. The default High setting continually attempts to render the animation at the highest possible quality. The Auto High setting, however, plays the animation at high speed until a problem occurs and then lowers the picture quality in an attempt to keep everything synchronized. You should test the Auto High setting because some versions of Flash Players seem to have difficulty with it. Another option is changing the frame play rate. The default is 12 frames per second. Keep in mind that a faster frame play rate results in faster play of those animation cells I mentioned earlier, so test for quality playback after dropping the frame rate.

Part IV: Finishing Touches


This section discusses how to publish your Flash movies and provides relevant HTML information necessary to provide context for the publishing process. ActionScript is introduced, providing foundation information for the Flash native scripting language.

Chapter 11. Publishing in Flash


Now that you have learned to create movies and animations with Flash MX, you should learn how to present these movies to your audience. Most Flash movies are published on the Internet on Web sites. Other movies are presented as just the movies themselves. To learn how to publish these movies online, you will learn the answers to these questions:

What are the different formats in which Flash can publish? Why are some formats preferred over others? How do you create an HTML page? How do HTML and Flash work together?

What Is Publishing?
Publishing files in Flash is the process of taking the movie you have created in the Flash MX workspace and creating a file that users can see. The files that Flash MX creates when you save your movie are viewable only in the Flash MX workspace. To create a file that is viewable by anyone with a Flash player (whether it's a stand-alone player, a Flash plug-in for your Web browser, or another program), you need to publish the file. Of course, before you publish anything, you should understand what you want.

Types of Web Formats


Flash supports a number of formats for publishing. The items in this list work in different contexts, so you need to know where your movie will be viewed before selecting a publishing format. The format choices are as follows:

.SWF. Files for a Flash Player. .HTML. The format for a basic Web page viewed on the Internet. The Web page will contain the Flash movie. .GIF. Static or animated GIF files, viewable in most browsers and imaging programs. .JPEG. Static image files, viewable in most browsers and imaging programs. .PNG. Another type of static image. .MOV. Apple QuickTime movies. .EXE. A self-contained Microsoft Windows program that includes a Flash player and the movie. .HQX. A self-contained Apple Macintosh program that includes a Flash Player and the movie.

Each of these file types has its own benefits and limitations. To help explain how these file types work, they have been categorized into the following four groups:

Interactive movie. This category includes: SWF, MOV, EXE, and HQX files. With ActionScript, you can create interactive movies that respond to the user. SWF files require a Flash player or Flash plug-in, in order to be viewed. SWF files are used when the published movie is to be viewed on the Internet. QuickTime MOV files

require the Apple QuickTime player or plug-in for your Web browser. The QuickTime player is easily downloaded. The stand-alone file types (EXE and HQX) run completely on their own. They have all the information needed to play the movie, including Flash Player. To further clarify, the EXE and HQX file types can run without an Internet connection; for example, if placed on a CD-ROM. Non-interactive movie. These movies, including animated GIF files, play continuously without user interaction. Animated GIF files can be viewed in browsers without a plug-in or special player, but are usually very large. Static picture. GIF, JPEG, and PNG files are created from only the first frame of the Flash movie or a keyframe with the label #Static. These pictures, although not interactive or dynamic, are useful in Web development. You can create an image to use as a background for a Web site in Flash, export the image as a GIF or JPEG file, and use it in the Web site's HTML files. Helper file. HTML files created by Flash assist in the process of moving your movie to the Web. These files do not contain the movies themselves, but contain information telling a Web browser how to display the Flash files.

Publishing Options
Flash can publish in lots of different formats as seen in the preceding list. Because of the sheer number of possible combinations, I will show you how to cover the available options and then publish a movie using a few standard and useful options. All the files types that Flash can publish to and the options for each file type are available by selecting File, Publish Settings or by pressing the shortcut Ctrl+Shift+F12 ( +Shift+F12 on the Mac). Now let's explore the Publish Settings dialog box.

Formats
The Formats tab allows the selection of each type of file you want to publish. Each type selected on the Formats tab results in a new tab for that particular file type. As you explore the different file types, the corresponding options are found on that coordinating tab. For example, if JPEG is selected on the Formats tab, a JPEG tab will appear.

NOTE You can select more than one file format for publishing. In most cases, at least two, if not more, file types are used.

Flash Options
First, let's look at the options for published Flash movies. Select the Flash tab at the top of the Publish Settings dialog box. In most cases, using the default publish settings found on the Flash tab of the Publish Settings dialog box will create a suitable file for use on the Internet.

NOTE Two schools of thought exist in regard to determining in which version to publish Flash movies. Some people believe that you should always use the newest technology and force users to upgrade Flash Player if necessary. This strategy may be an inconvenience to users, but it allows the developer to use the newest tools and features. The other option is to publish to the lowest-level player that implements the features you need in your movie. Users then most likely do not need to upgrade Flash Player, although the movie may not do everything that was intended. The most useful template is Flash Only (a selection on the Template drop-down list on the HTML tab in Publish Settings), which tells the Web browser to open the Macromedia Flash Player 6 plug-in. With this template, if the browser cannot open the plug-in because it is not installed, the browser tries to install the plug-in.

You have lots of possibilities for creating SWF files from Flash. One of the choices, located with Options on the Flash tab, is Generate size report. This selection creates a report to see how large each piece of a movie is. The report is a text file (.txt) found in the same folder to which the movie was published. Let's look at a movie that was created specifically to be reported on. The movie used in this example consists of two scenes. The first scene consists of 25 frames that include:

A shape tween of a rectangle that becomes a circle A shape tween of a circle that becomes a rectangle

The second scene is only 20 frames long and has the following items:

A motion tween of a rectangle moving from the bottom to the top of the frame A motion tween of a rectangle moving from the left to the right A motion tween of a circle moving from the upper-left corner to the lower-right corner of the frame Text that stays in the center of the frame

This movie was published and a size report created. (I cover how to do this task in depth later in this chapter). The size report was placed in the same folder as the original FLA file. Looking at the report file in a text editor, you see a few items:

The next section of the report is only three columns wide and includes:

The next section of the report shows a breakdown of the symbols used in the movie.

The next section of the report shows sounds in the movie. The column headers are in the file, even though no sounds are used in the movie. The columns show:

Finally, at the end of the report is information about all the text strings used in the movie. The information includes:

In a big moviewith credits, captions, or lots of other moving textthis section is big. All the information in the size report is intended to help isolate areas of the movie that could be changed to make the final, published movie smaller. You should look at a frame or tween that is much larger than the other frames or tweens to determine whether you can do anything to simplify it. One big space-saver is to make sure that any shape used more than once is converted to a symbol and that instances of that symbol are used wherever possible.

HTML Options
If you have checked the HTML check box on the Formats tab of the Publish Settings dialog box, the HTML Options tab is available. This tab contains file settings that assist in putting your movie on the Web. (I have mentioned a few concepts here and will cover them more fully in the "HTML Basics" section later in this chapter.) The first group of options noted affects the guiding rules that format your movie and the size of it.

The next selections on the HTML tab affect how your movie plays to the view.

The following items provide instructions for the browsers (Internet Explorer and Netscape, for example) as to how they should handle your movie.

GIF Options
GIF images are one of the two standards for Web graphics. (The other standard is JPEG images, which I cover in a bit.) GIF images have two useful features: the ability to create animated images and the ability to create images with transparent backgrounds. When a GIF file is published, you have a number of options to consider. View the GIF tab in the Publish Settings dialog box. I will discuss each selection and its corresponding options. The selections in the first list affect the size of your movie and how it behaves when called to play.

NOTE Animated GIF files get very large very quickly. The GIF equivalent of a simple, small Flash movie could be more than 100 times bigger than the original Flash movie. The movie created for the samples in this chapter is a 2KB SWF file. The GIF file measures 102KB. The selections in the following list affect color and how it is handled in your Flash movie.

JPEG Options
JPEG images are the other standard image for the Web. JPEGs are 24-bit colored images that use compression to ensure that the image files are small. You have only a few options to consider when you are publishing to a JPEG file.

PNG Options
PNG images have many of the same options as GIF images. The selections found in this list affect the size and color of your movie.

QuickTime Options
QuickTime is a movie format created by Macintosh. QuickTime movies require either a QuickTime player or browser plug-in installed on the computer. When Flash publishes to a QuickTime movie, it creates a QuickTime track that contains the entire movie. If the Flash movie contains a QuickTime movie (as an imported symbol, for example), each included QuickTime movie is placed on its own track. Because this book is about Flash, and not about QuickTime, I only highlight its options here. You have a number of possibilities for publishing to a QuickTime movie:

NOTE To publish a Flash movie to QuickTime format, you may need to set the version on the Flash options tab to Flash Player 5 or earlier. If you try to publish a movie targeted to Flash Player 6 as a QuickTime movie, you will probably get the error message, "The installed version of QuickTime does not have a handler for this type of Macromedia Flash movie."

Publish a Movie
Now that I have covered just about all the options you can choose, you can export a movie. Prepare a movie to be published.

Now make your selections on the Flash tab.

Make your HTML selections on the HTML tab.

Publish your movie. 1. 2. 3. 4. When all the settings are properly configured, click on Publish. Wait until Flash finishes publishing the movie and then click OK. In Windows Explorer, find the folder in which the original Flash FLA file was saved. Double-click the HTML file to open it in your favorite Web browser.

If you need to publish to the Web, the rest of the publishing instructions vary depending on the type of Web server you are publishing to. You probably need to use an FTP client and copy both the HTML and the SWF files to the server.

HTML Basics
So far in this chapter, I have mentioned HTML files quite a bit, but I have yet to discuss what they are or how they work. HTML is short for HyperText Markup Language, the language of the Internet. All Web browsers understand a flavor of HTML, although each browser behaves differently. Microsoft Internet Explorer and Netscape Navigator interpret the same tag and possibly display slightly different results. After I cover the basics, look at one of the files that Flash created for you when you published a movie. NOTE HTML is a subject for an entire book. This chapter touches on a few basic topics. For a more in-depth discussion, check out Learn HTML in a Weekend, 3rd Edition, by Steve Callihan, or Hands-On HTML, by Greg Robertson and Simply Written, Inc. You can also check the numerous online resources for learning HTML including:

http://www.w3.org (The World Wide Web Consortium) http://hotwired.lycos.com/webmonkey/ http://webreference.com/html/ http://www.htmlgoodies.com/

Again, there are many, many Internet resources out there, check them out and see which you prefer.

HTML Structure
HTML files are text files that have a basic structure. You can open HTML files in your favorite text editor (such as Notepad) or in special HTML editors, like Macromedia's Dreamweaver. The structure is referred to as a tagged structure. The file contains text that can be displayed, and this text is surrounded by tags that tell a Web browser how to display the text.

<HTML>
The HTML tag is used to tell the Web browser that this is indeed an HTML file. All HTML files should start with an opening tag
<HTML>

and end with a closing tag


</HTML>

Let's look at these two tags for a moment. The angle brackets, < and >, designate tags. The forward slash (/) indicates a closing tag. Tags in HTML should be matched, which means that you should have both an opening and closing tag. Get into the habit of always closing HTML tags (you will soon learn the few that do not get closed). If the wrong tag is left open big problems can result in some browsers and that open tag can be hard to find in a long page of code. It is generally considered bad form.

<HEAD>
The header block, denoted by the <HEAD> tag, can contain such information as the document's title, any scripting, and Meta information (including keywords and description) that can be used by search engines.

<TITLE>
The contents of the title tag appear in the Web browser's title bar. Again, this tag is located within the <HEAD> tag.

<BODY>
The body section follows the header section and contains the bulk of the information in the HTML file. As previously mentioned, HTML is vast enough to fill its own book with information and several books, including those recommended, exist as resources for you. Text in the body tags can be formatted much like text can be formatted in a word processing program. Do some research on Cascading Style Sheets to learn the preferred methods.

<H1>, <H2>, <H3>, <H4>, <H5>, and <H6>


Heading tags display the text contained inside of them as section headers. <H1> tags contain large text, and each subsequent numbered header has smaller text.

<P>
Paragraph blocks contain text that should be grouped together and followed by a line break. Because the text in an HTML file is displayed continuously, except when line breaks are intentionally placed, this tag is helpful.

<BR>
The line break tag is one of the few tags that are not paired. There is no closing </BR> tag. <BR> forces the end of a line.

<A>
Anchor tags are some of the most useful tags in HTML. They create hyperlinks, or links, between pages. Anchor tags can contain several attributes. The most important attribute for an anchor tag is the HREF, or the URL that the link connects to. This sample anchor tag takes users to http://www.premierpressbooks.com when they click on the words Premier Press Web Site.
<A HREF="http://www.premierpressbooks.com">Premier Press Web Site</A>

<IMG>
This tag inserts an image and takes several attributes:

SRC. The URL of the graphic file ALT. A text string that is displayed either when the image cannot be loaded or when the user hovers the mouse cursor over the image for a moment WIDTH. The width of the image in pixels HEIGHT. The height of the image in pixels

HTML in Practice
Now that you've been introduced to some of the commonly used HTML tags, let's put them together in a simple Web page and view the resulting output. This file, when opened in a Web browser, creates the following Web page.

The status bar at the bottom of the browser window shows the URL that the link Flash! directs the user to.

These tags are not all of the HTML tags, by any stretch of the imagination. There are many more tags used in HTML, along with numerous options for some of the tags in the list. The tags I have covered will at least get you started. NOTE One of the simplest ways to learn HTML is to use a feature that exists in most Web browsers: the ability to view the source code for the Web pages you visit. In Microsoft Internet Explorer, you can select Source from the View menu to

see the source code for the current page or right-click on the page and choose View Source from the context menu. In Netscape, select Page Source from the View menu. Look at the code, see what the results of some of the tags are, and experiment.

Chapter 12. Simple ActionScript


In this chapter, you will learn the answers to these questions:

What is ActionScript? What are the similarities and differences between ActionScript and JavaScript? What are the basic concepts of programming? What are the building blocks of ActionScript and how are they used? How do you use Flash's Action panel? How do you construct a simple script?

Thus far in this book, you have created movies with Flash that start at the beginning and play through to the end. These movies, although interesting, are the same the first time and the hundredth time you play them. This chapter helps you learn how to create interactive movies, or movies that respond to input from the person who is watching them. Of course, this concept entails the use of a scripting language. Yes, you have to learn some simple programming. At first, it may seem difficult, but programming gets easier with practice. You may need to read this chapter a few times and refer to it when you are creating interactive content.

What Is ActionScript?
Flash allows you to create simple animations or complex interactive games. The choice is up to you. However, to talk to Flash and tell it how you want it to respond to the user requires speaking to Flash in a language it understands. The language that Flash understands and can work with is ActionScript. The ActionScript scripting language allows the programmer to control objects and movies and to get Flash to respond to the user. Before I continue, I should cover a few basic elements of programming. Most programming consists of creating simple mathematical equations. Programming languages, like ActionScript, allow a program to be broken into small pieces called functions. Breaking up the program into smaller parts provides several benefits. For example, the code can be organized into logical pieces. If the program will perform several different actions and operations, the manner to carry out each of those processes can be placed in its own function. Also, code that is used multiple times can be placed in a function. Programmers do this so that they can easily use a long process with minimal work on their behalf. Any changes that must be done to the logic in a frequently used piece of code, therefore, only need to be updated once if a problem appears. Another advantage of using functions is that they can be given information to use when they are called. The information passed to a function is an argument. Arguments can be extremely helpful. For example, one of the functions of most calculators is to compute the squares of numbers, such as "two squared equals four." The calculator program probably has a Square() function that takes a number as an argument. The Square function then multiplies the number by itself and gives the resulting number as a return value. Return values are another benefit of functions. A function can calculate an answer based on input and give the answer back through a return value. Keeping these concepts in mind, let's look at a few building blocks of ActionScript.

ActionScript and JavaScript Similarities and Differences


ActionScript is loosely based on JavaScript. If you have used JavaScript in Web site development, you should be able to learn ActionScript relatively quickly. If you are not comfortable with JavaScript, you can skip this section, or you can refer to it if you also want to learn to use JavaScript. The syntax for ActionScript is almost identical to that of JavaScript, which can make reading and understanding code much easier. However, JavaScript supports a number of features that ActionScript does not, including the following:

The Document, Window, and Anchor objects and other objects specific to Web browsers Exception handling through the use of try, throw, and catch statements The Function constructor

A number of items behave differently in ActionScript when compared with their JavaScript counterparts. These differences include the following:

The toString method in ActionScript works as toString in JavaScript except when the variable being converted is undefined. The ActionScript version of toString returns an empty string, not the string undefined. This was implemented to provide backward compatibility with scripting in Flash 4. When undefined is used in numerical calculations and evaluations in ActionScript, 0 is the result rather than the JavaScript result of NaN (Not a Number). When a string in ActionScript is used as a Boolean data type, the string is converted to a number and the resulting number is then converted to a Boolean value, where 0 returns false and everything else is true.

This description of differences between JavaScript and ActionScript is not comprehensive, but it should help as a starting point.

Basic Programming Concepts


Programming is a complex process that hopefully results in software (or Flash movies) that acts the way you intended it to act. A few universal concepts apply in programming, no matter what language you use. You'll learn about some of them in this section. All programming languages have a structure that programmers need to follow so the computer understands what the programmer wants it to do. Remember that computers are not smart and that they can understand only certain instructions given to them in the binary language (using ones and zeros). Programming languages provide a simple way to give the computer instructions. They also are human readable, which means that program code can be read and understood by a person who can read the language in which the program was written. ActionScript's structure is relatively simple: You can associate scripts in ActionScript with different elements in the movie, including each keyframe and each instance of a button symbol. Like any language, ActionScript has rules. In English, a sentence should contain at least a subject and a verb and end with the appropriate punctuation mark. Spoken languages have lots of rules for their use and often have many exceptions. Programming languages have fewer rules, but few (if any) exceptions. As in English, the meaning of a statement may change depending on the order of its words, the punctuation used, and the words themselves.

ActionScript is similar in this regard. Most sentences in English end with a period. Statements in ActionScript end with a semi-colon. In English, sentences are grouped together into paragraphs; in ActionScript, statements are grouped together into functions. In English, paragraphs are delimited by a return and an indent; ActionScript uses curly braces, { and }, to hold the contents of a function. These important points are summarized with this bulleted list.

ActionScript statements end with a semicolon. ActionScript statements are grouped together in functions. ActionScript uses curly braces to hold the contents of a function.

Functions can use certain information to determine what the function should do. Information used by a function in this manner is a parameter. Parameters in ActionScript are contained in parentheses.

Parameters are pieces of information passed to a function. Parameters are passed to functions in parentheses.

In English, the meaning of a word may depend on whether it is capitalized. ActionScript cares about the case of words in only a few instances, when it is working with a short list of words reserved for use by ActionScript. You should use these special, reserved words, or keywords, in the correct case, which is all lowercase. Other wordsfor example, variable namesdo not depend on case, so, as far as ActionScript is concerned, BoB and bob are the same. Working with a program is much simpler, of course, if you use the same case consistently throughout the program.

ActionScript is typically not case-sensitive. Keywords should always be used in the correct case lowercase.

The period, or dot, has special meaning in ActionScript. When you have an object, you can access the properties of that object by using the period. (I will cover this concept later in this chapter.) One other important item to consider is the comment. A comment is a note to the programmer (written by a programmer) that ActionScript does not need to know about. Comments are preceded by two forward slashes (//) and apply until the end of the line. Anything inside a comment is ignored by Flash and ActionScript and exists only to explain to a programmer what is happening. NOTE ACTIONSCRIPT KEYWORDS Only 20 keywords are used in ActionScript. Some you rarely use, although others may appear quite often in your code. Keywords cannot be used as variable names or as function names. The keywords are shown in this list:

break case continue default delete else for

function if in instanceof new return switch this typeof var void while with

ActionScript and the Actions Panel


In Flash MX, just about everything you can create has properties that you can access through various panels. ActionScript is no different. The Actions panel can be opened by selecting Window, Actions or by pressing the keyboard shortcut F9. This panel, which resides under the Stage work area, is complex. Let's look at how this panel works and then cover some of the basic concepts of ActionScript. The Actions panel has two different views: Normal mode and Expert mode. If you need to change from one mode to the other, click on the shortcut menu in the top right corner of the panel. Normal mode simplifies scripting, and Expert mode allows for more flexibility (you can type code directly in Expert mode). When you open the Actions panel, it opens in the last mode that was selected. In Normal mode, you notice lots of buttons and areas in the panel:

The items in the list above help explain the layout of the Action panel. Now let's take a look at the Actions Toolbox. You will likely use this quite a bit as you start out in Action Script.

The list below highlights many of the resources found in the Actions panel.

The next list of options identifies tools to assist with editing and programming.

That is a long list of things you can work with when writing scripts.

Earlier, I mentioned Expert mode for the Actions panel. In Expert mode, most tools in the Actions panel are the same, with the following exceptions.

The Building Blocks


To become better acquainted with ActionScript and how it works as a language, you need to spend some time learning vocabulary. The next few sections focus on the different components of ActionScript.

Variables and Constants


Almost all programming languages allow the use of variables and constants. Constants are a simple way to keep track of things that do not change while the program (or script) is running. If you think about math, constants are things like pi (a number that always is 3.14) or the number of sides in a triangle. These elements are known quantities. Variables are elements that may change (or vary) during the time a program runs. For example, when you open your Web browser and type the URL of a site you want to visit, the string you type in is stored in a variable and used by the program. Later, you might type another address, and that value is stored in the same variable. Let's look at how Flash lets you use variables. Variable Types Flash uses three types of variables:

Numbers. Numbers are either integers or decimal numbers. Some examples are 12, 10.5, and 9999.99. Strings. Strings are text strings (or phrases), like "Flash is cool." Most feedback to the user occurs by using strings. Objects. Objects are a special group of variables, made up of other properties and methods. Properties are variables that help describe the object, and methods are functions that the object can perform or that other elements can do to the object. You refer to objects in two different ways. Object definitions describe what is in an object, and some instances of an object follow the definition, but contain information specific to a certain instance of it. For example, say you create an online store with a catalog. One object you might need is a Product, which contains the information for an item sold on the site. The object might contain several properties, including an SKU number, a name, a description, a price, and the number available. One method might be UpdatePrice, which changes the price of the instance of the Product you are working with when it goes on sale. One instance of a

Product might be this book, in which the SKU is the ISBN number, the name is the title, and the description is "The best Flash MX book you can get," for example. Objects can be a tricky concept. However, by using objects in scripting (which you do later in this chapter), the concept becomes clearer. Fortunately, ActionScript makes things easy by keeping track of a variable's type for you. Most of the time, you do not need to worry about the variable type. On the rare occasion that you do need to ensure a variable is of a certain type, you can use one of two special functions: Number and String. Number takes a variable and returns a number. String takes a variable and returns a string. You will use these functions later in this chapter, also. Variable Scope Scope, which is important when you are working with variables, refers to where the variable exists and when it can be used. Flash uses three possible scopes: Local, Timeline, and Global. Local variables are available in the same part of the program in which they are declared. Local variables exist between curly braces. Often, a variable is needed in only a specific function. Because variables consume memory when they are used, it makes sense that variables needed in only one area of code are created in only that area of code. Timeline variables can be accessed from anywhere in the Timeline, allowing a simple way to access variables that are used often. Keep in mind, however, that this convenience comes at the cost of memory usage. Global variables can be used from anywhere in the script. This variable type is handy for information you need available from every section of the script, but can cause problems, as you will see later in this chapter. Using Variables Now, let's try your hand at using variables. NOTE The code samples in this chapter serve to familiarize you with ActionScript and scripting in Flash. Most of these examples do not do much in the way of functionality, but they help you understand some interesting and important concepts. First, create (or declare) a variable in the first keyframe of Layer 1 in a new movie. You then set the value of the variable and change the value.

Next, name and configure your variable.

Congratulations! You have now written some code. The code does not do anything useful yet, of course, but you have made a start. Most people find that objects are a confusing concept the first time around. An often-used example of an object is a student. The Student object often contains a number of items, including a student number (a Social Security number, for example), last name, first name, address, and a bunch of other characteristics. Looking at a limited example can keep things simple, so this example contains only the student number, name, and address.
Student = {StudentNumber:12345, FirstName:'Bob', LastName:'Jones', Address:'123 Main St.'};

The curly braces in this example indicate that Student is an object and that it contains the information between the braces. Commas separate the different properties of the object, and the colons indicate that the value that follows is the desired value for the property. The single quotes indicate that the value is a string, unlike the number value following StudentNumber.

What Are Conditionals?


Conditionals allow a script to behave differently in different situations. There are two types of conditional statements: If statements and Switch statements. Basic If Statements The if statement is the simplest conditional statement to understand. The format is
if (x == 5) { y = 10; }

Examining this code, you see a few interesting points. First, the structure of an if statement is the word if followed by a conditional statement in parentheses. If the statement in parentheses (if x is equal to five) is true, then the code between the curly braces runs. If not, the code in the curly braces is skipped. Notice the double equal signs in the condition. That's not a typo. In ActionScript, a single equal sign sets the variable on the left to the value on the right. A double equal sign is used for comparing two values. Triple equal signs (===) comprise a strict equality comparison in which the data types of the variables being compared are not converted to a similar data type. The legal comparison operators are the following: Comparison Operator Equal to == Symbol

Comparison Operator Strict equality Greater than Less than Not equal to Greater than or equal to Less than or equal to === > < != >= <=

Symbol

NOTE With an if statement, many programmers would argue that the curly braces are not needed for a 1-line if statement. Technically, in the preceding case, you could leave out the braces. However, bugs are often created by programmers who leave out the braces and then return to add more lines to the body of the if statement. In good programming practice, you include the braces whether they are needed or not. The ifelse Statement A more complex if statement is the ifelse statement.
if (x == 5) { y = 10; } else { y = 20; }

In this statement, if x equals 5, then y is set to 10. If x is not equal to 5, then y is set to 20. This code example is a simple extension of the if statement.

Switches
Switches are a slightly more complex type of conditional statement that allows for numerous possible cases. A switch tests a value against several cases and runs the code for a case if the case and the value are the same. A new reserved word, break, comes out of the switch statement. Here is some sample code you can analyze.
var theVariable; var x; theVariable = Number(InputTextField.text); switch (theVariable){ case 1: x = 1; break;

case 10: x = 5; case 11: x = 10; break; default: x = 0; break; }

This example is a little complex, so take it slowly. An assumption made in this example is that a text box is set up to be an input field named InputTextField. The text in InputTextField is converted to a number and stored in theVariable. The switch statement then tests the value of theVariable against each of the cases listed. If theVariable equals 1, x is set to 1 and the break jumps you out of the switch statement. If theVariable equals 10, x is set to 5. Then you continue through case 11, set x to 10, and finally break out of the switch statement because no break statement occurs between case 10 and case 11. If theVariable equals 11, x is set to 10. If theVariable does not match any other cases, the default case is run, setting x to 0. NOTE Many bugs are created with switch statements when programmers leave out a break statement. You should always double-check switch statements to avoid this type of omission.

Looping Constructs
Loops allow for the repetition of a task numerous times. ActionScript uses several types of loops.

for forin while dowhile

Let's look at examples of each one. For Loops For loops are a great way to perform a task a set number of times. For loops set up a counter and iterate (or add one to) the counter each time through the loop. I introduce two new concepts in the following example: the ++ operator, which adds 1 to the variable that precedes it, and the trace function, which prints the string that is passed as an argument in the Output panel.
for(i = 0; i < 10; i++) { trace("the counter = " + i ); }

This example sets i to zero, runs 10 times (starting with zero and running until nine for a total of 10 times), increasing the value of i by one each time as long as i is less than 10, and creates the following output.
counter counter counter counter counter counter counter counter counter counter = = = = = = = = = = 0 1 2 3 4 5 6 7 8 9

NOTE Similar to the ++ operator, the -- operator decreases by 1 the variable that precedes it. Forin Loops Forin loops are fantastic for working with objects. You can iterate through each property in an object and manipulate the property. In the following example, you create an object named CatalogItem and print each of the properties and their values.
CatalogItem = { SKU:'12345', name:'Book', price:19.95 }; trace("A CatalogItem has the following properties: "); for (property in CatalogItem) { trace(property + " : " + CatalogItem[property]); }

This code produces the following output.


A CatalogItem has the following properties: SKU : 12345 name : Book price : 19.95

While Loops While loops are another tool for repetitive tasks. These loops use a test condition and run as long as the condition is true.
var whileTest = 0; while (whileTest < 5) { trace ("whileTest = " + whileTest); whileTest++;

This example results in the following output.


whileTest whileTest whileTest whileTest whileTest = = = = = 0 1 2 3 4

While loops do not run if the condition is false the first time it is hit, which is different from dowhile loops, which always run at least once. Dowhile Loops Dowhile loops are similar to While loops, but always run through once before checking the conditional statement. Look at the following example and the resulting output.
var test1 = 0; do { trace("test1 = " + test1); test1++; }while (test1<3); var test2 = 0;

do { trace("test2 =" + test2); }while (test1>3); test1 test1 test1 test2 = = = = 0 1 2 0

Notice that the second dowhile loop ran once, even though the condition statement is false. NOTE When using any type of loop, you can create an infinite loop, or a loop that never ends because of a mistake in either the end condition or the iterator. Infinite loops create all sorts of problems, including crashing Flash. Be careful to doublecheck to ensure that at some point, no matter what happens, the loop ends.

Arrays
Arrays are special types of variables that contain several values. Arrays are useful in a number of circumstances. A new operator associated with arrays, the array access operator, is a pair of brackets ([]). Arrays contain a set number of elements, and each element is accessed via its index. Indices are numbers, starting at 0. You can create an array in several ways, and the selection of the method chosen depends on circumstances. The following example creates two arrays and then uses trace to print the contents of each one. As you may have guessed by now, trace is useful for displaying what is being called by your function.

myArray = new Array(3); myArray[0] = "Hello"; myArray[1] = "There"; myArray[2] = 10; for (I=0; I < myArray.length; i++) { trace("myArray[" + i + "] = " + myArray[i]); } myArray2 = new Array(1, 2, 3, 4, 5, "done"); for (I=0; i < myArray2.length; i++) { trace("myArray2[" + i+ "] = " + myArray2[I]); }

This short script, when run, will display the values of the three elements in myArray and the six elements in myArray2.
myArray[0] = Hello myArray[1] = There myArray[2] = 10 myArray2[0] = 1 myArray2[1] = 2 myArray2[2] = 3 myArray2[3] = 4 myArray2[4] = 5 myArray2[5] = done

Applying What You Learned


Now you have learned some of the building blocks of ActionScript. The next step is to put these pieces together and apply what you have learned. Start by working through some code examples.

Example 1 Square()
Let's return to an example I mentioned in the first section of this chapter, the calculator function Square(). The Square function returns the square of an argument. To create an example that is meaningful, you need to do several things:

Create a text box where the user can enter a number.

Create a button so that the user can click to calculate the square of the number that is entered. Create another text box to display the answer. Write the Square function. Write a function that is called when the user clicks on the button. This function gets the number in the first text box, named Square, and puts the result in the second text box.

Adding Text Boxes Start by creating the user interface elements.

Creating a Button

You cheat a little when you create the button the user clicks on. You could create a button symbol or import an existing button from a library, but, instead, you use one of the Flash UI components and learn a bit about these new tools. Now you continue with the same Flash file you have been working with.

Creating Functions Now that you have the interface, you need to write some code. You start with the Square function. NOTE For this short section, you will see the Action panel's Normal mode at work. In the future, you will use Expert mode. By using Expert mode, you can see much more code at one time to help give perspective to the work you are doing.

You now have a simple function that multiples a number times itself resulting in that number's square. Now you need to create a function that gets the number the user typed, calls the Square function, and updates the Result text field.

Now, you will need to tell Flash to call the HandleSquareButton function, after the Square button is pushed. This task is simple.

Congratulations! You have finished your first program in ActionScript. If you prefer to use Expert mode, here is the code you should type (see figure).

NOTE From this point on in the chapter, you will work in Expert mode because you can more easily see more than one line of code at a time. If you choose to work in Normal mode, you can still check your work against the code listed here if you switch to Expert mode.

Example 2
Now that you have your first simple Flash program, you also have your first bug. The problem is that if you type anything except a number in the Input Text field, you get an answer of NaN. How can you fix this problem? The following section explains. You can use an if statement to disallow text input in the preceding squaring example. An event named onChanged exists for text fields. When the text is changed, this function is called. If you test the text to see whether it is a number and disallow the text if it is not during the onChanged function, you will fix the bug. Follow these steps:

Example 3
In this last example let's create something fun. First, you will create a simple shape. Next, you will add some action to the shape. Upon completion of the project, your shape will act as a mask allowing the background layer to show through as the shape enlarges or shrinks while being dragged. You can really create some neat effects here. This example makes use of the naming convention tip mentioned in Chapter 5. Now is a good time to get into the habit of naming your symbols with suffixes. The practical application is up to you!

1. Create a new movie. 2. In the first keyframe of the first layer create a design for your background. 3. Convert the background shape into a symbol.

4. Name the symbol whatever you like with the appropriate suffix (mysym-bol_mc). 5. Be sure to select Movie Clip in the Properties panel and type in the name of your symbol in the box for the instance name. 6. Insert a new layer. In the first keyframe of the second layer, draw the shape that you want to be able to move.

7. Select Movie Clip from the drop-down menu in the Properties panel and type in the name of your symbol in the box for the instance name. 8. Add a third layer and name it Actions Your basic objects have been created. Now transition to the Actions panel where you will add the code. 1. Click the keyframe in the Actions layer and open the Actions panel. 2. Next add the setMask method, allowing you to dynamically identify any movie clip as a mask of any other movie clip instance. 3. Declare your variable, creating a starting size for your movie clip.
back_mc.setMask(circle_mc); var status ="Big";

NOTE As you type in myMovieClip_mc, notice what happens when you type the period. Recalling that we are in Expert mode, when you press the period key, possible methods for your movie clip display. You will find setMask in the list. Now create two functions to scale your shape larger and smaller. Notice the if and else if conditional statements. Also, _xscale and _yscale are properties of the shape movie clip you created. You are telling the shape to expand (by a value of

5, with x and y in proportion) until a size of 350 is reached and then shrink in the same manner until a size of 100 is reached.
function scaleMe() { if(status =="Big") { circle_mc._xscale += 5; circle_mc._yscale +=5; if(circle_mc._xscale > 350 && circle_mc._yscale > 350) { status = "Small"; } } else if(status == "Small") { circle_mc._xscale -=5; circle_mc._yscale-=5; if(circle_mc._xscale <100 && circle_mc._yscale < 100) { status = "Big"; } } }

Finally, add the onPress and onRelease methods to your shape movie clip, providing directions for when the mouse button is clicked and when it is released, as well as dragging.
circle_mc.onPress = function() { scaleInterval = setInterval(scaleMe,50); this.startDrag(); } circle_mc.onReleases = function () { clearInterval(scaleInterval); this.stopDrag(); }

Save your movie and select Control, Test Movie to view what you've created.

Hopefully, this example provides some insight into the many cool features of Flash MX. The more you work with ActionScript, the more the pieces will start to fit together.

Appendix A. Quick Reference Glossary


Knowing Your Workspace Frequently Used Panels Flash Functionality Components

Knowing Your Workspace


The parts of the workspace listed below will become the building blocks of your development area as you continue to develop in Flash. Timeline. You will see a series of vertical rectangles whenever you open Flash MX. The rectangles are white with a gray rectangle in every fifth position. The amount of time allocated per movement in the Timeline provides Flash with needed instructions for how to play the movie.

Frame. The rectangles just mentioned are frames. Frames "hold" time.

Keyframe. Keyframes are frames of action. A new occurrence that happens in your movie is denoted by a keyframe. The typical procedure is "enter keyframe and add action or change."

Layers. Layers are located to the left of the Timeline. They are identified by a name with a horizontal icon to the left of the name. Layers are used to organize your movie.

Stage. The Stage is below the Timeline. This large, white space is your work area. There, you do everything from creating the symbols to be used to laying out the look of your movie.

Frequently Used Panels


Flash offers a variety of panels allowing you numerous options. You will use some panels, however, more regularly than others. They are described below. Properties panel. This panel is located below the Stage. If the panel is not selected, you can display it by choosing Window, Properties. This panel is important. When you're selecting anything on the Stage, that object's particular properties are displayed and can be edited in the Properties panel.

Actions panel. You use this panel to add ActionScript toyour movies. The panel, which has a toolbox that expands for navigation, works in Normal mode and Expert mode.

Color Swatches panel. This panel provides swatches of quick color choices, along with ready-to-use radial selections.

Color Mixer panel. This panel enables you to create custom colors, affecting the type of gradient applied and its alpha setting, for example.

Flash Functionality
Symbol. The graphical objects in your movie should be symbols. These objects enable Flash to export smaller files.

Button. This type of symbol provides a button with its different states.

Movie clip. This type of symbol has its own timeline and can be independently animated.

GIF. This commonly used image type can be animated or include transparency.

JPEG. This is commonly used image type.

Motion tweening. This functionality basically moves an object from one location to another.

Shape tweening. This functionality morphs an object from one shape to another (and also works with text).

Shape hint. This feature is used with shape tweening to instruct Flash about how the shape change should occur.

Alpha. This feature, found on the Color Mixer panel, controls the transparency of an object.

Components
Find the Components panel by selecting Window, Components. On this panel, Flash provides ready-to-use objects that you can drag to the Stage to perform common tasks. CheckBox. Adds to your movie a common check box where multiple selections can be made.

ComboBox. Adds a combo box or dropdown box to your movie.

ListBox. Adds to your movie a list box where items are viewable and scroll vertically.

PushButton. Can serve numerous functions, such as a Submit button or Reset button, for example.

RadioButton. Adds radio buttons to your movie, where only one selection can be made.

ScrollBar. Adds the scrolling function (a good feature not to have to create from scratch).

ScrollPane. Adds the scrolling function both vertically and horizontally.

Appendix B. What's Next?


Now that you have a solid grasp of the fundamentals of Flash, where do you go from here? There are a number of development possibilities. The next two sections can help you better define that path. "Helpful Resources" points out good places to look for information and "New Directions" provides examples of new development venues.

Helpful Resources
Many different sources of resources are available, including Web sites, newsgroups, forums, and listservs. Because Flash is the industry standard in its field, many resources exist to help you further your knowledge. Macromedia also has extensive information for developers, and some of those resources are listed in this appendix. The Flash Online Forum provides a basic introduction on how to get started. You can select from several categories, including the following information:

Flash general discussion Flash handhelds Flash site design Flash remoting Flash exchange extensions Flash communication server

Browsing through information found on forums or other community discussions is a good way to broaden your knowledge of the Flash MX capabilities. You should also read about the kinds of issues other developers are interested in or struggling with. Forums also provide a place to post questions. The Macromedia Exchange for Flash area provides links to various new features that developers have created for Flash. The extensions found there are free for your use. If a charge is required for the extension, the link takes you to the author's home page. Extensions are a great way to enhance your Flash movies with new features. The Samples and Tutorials link is a good place to find useful information. Its Keyboard Shortcuts section can help enhance your efficiency. Also, one section contains several sample files available for downloading. The Support Center provides a library of resources you can search for assistance with troubleshooting. This area includes such items as Tech Notes, FAQs, and Release Notes. The Macromedia site is certainly a good place to start when looking to enhance your knowledge or troubleshoot, although many other good resources are available.

Flash Kit. Offers valuable resources, including a conference and an expo; http://www.flashkit.com. Virtual-fx.net. Offers many tutorials with a search feature as well as a variety of other resources; http://virtualfx.net/vfx/index.php. Flashforward. Publishes an e-mail list and sponsors a conference with a Flash Film Festival! Read about the conference and its offerings at http://virtual-fx.net/vfx/index.php. Flashmagazine. Offers a variety of insight on what's happening in the Flash community; http://www.flashmagazine.com/html/. Talk about extending the uses of Flashthis magazine keeps you informed.

New Directions
As you see as you begin to review some of these resources in the previous section of Appendix B, the Flash capabilities have grown exponentially. This section is meant to whet your appetite to discover some of Flash's new capabilities. For example, you can now develop applications in Flash for PocketPCs, extending Flash's more common Web environment. This option was briefly discussed as a publish setting in Chapter 11. Imagine the possibilities! If this is an area of interest to you, be sure to research the benefits and limitations. With the help of Macromedia Cold Fusion MX, you can add data exchange to your Flash application. You can see an example of an application of this nature by clicking the Make a Reservation button at http://www.broadmoor.com. (You have to get into the accommodations area to find the button). You can benefit from the intense functionality without the application having to make several trips to the server each time a new call is made. These illustrations just touch on the many possibilities for development with Flash MX. Hopefully, your interest has been piqued. Enjoy yourself as you discover more and truly become an expert!

You might also like