The Flash Anthology: Cool Effects & Practical ActionScript – Chapter 1: Flash Essentials

Life without Flash would be uninteresting and mundane. Flash sites are to static HTML sites what a family-size, deep-crust pizza with all the toppings is to a piece of toast. Many of today’s big-impact sites are either full-blown Rich Internet Applications (RIAs) or a prudent blend of HTML and Flash. This careful melding of technologies, coupled with seamless integration, means the difference between an online experience that’s striking, and one that’s utterly forgettable.

Sites that use Flash as the sole medium for conveying their message, and sites that use several mini-Flash applications to punctuate static HTML, have a common underlying theme: they all harness the power of Flash to create lightweight vector- (or coordinate-) based interfaces, applications, and animations. Flash has become a powerful tool for the communication of ideas, its capabilities having inspired a large and passionate following of dedicated users.

This series starts by explaining the essential knowledge any designer or developer will need to know in order to use the package, then moves on to explore in detail the areas of animation and sound. It comprises 3 articles:

Chapter 1: Flash Essentials
If you’re new to Flash, this chapter will give you a solid grounding in the program’s interface, as well as a fundamental understanding of the ActionScript dot notation. Tips and techniques for working with ActionScript and the timeline are also included. Finally, I’ll walk you through a few organizational guidelines. This chapter begins below.

Chapter 3: Animation Effects
The question of whether to use timeline-based or scripted animation is one every Flash developer asks at some point. We’ll explore the principles behind these effects and attempt to put the timeline vs. script debate to rest once and for all. The basic building blocks provided in this chapter will have you creating stylish animations in no time!

Chapter 5: Sound Effects
One of the most underemployed, yet effective additions to a project is sound. Appropriate sound effects can enhance the impact of movement, provide feedback to users interaction, and build atmosphere. In this chapter, we analyze when sound should be used, how to choose the right sound clip for the job, and how clips can be imported and exported easily. We explore volume and panning, then build a mini sound player, random track sequencer, and much more.

The Book

These 3 chapters are excerpts from my new book, The Flash Anthology: Cool Effects & Practical ActionScript. The book contains a total of over 60 ActionScipt solutions to common problems in Flash. Every solution you’ll ever need for your Flash projects, from text and video effects, to debugging and using external data in your applications, is covered in this 455-page reference. All the code included in the book is available in a free downloadable archive.

If you’d prefer to read the Adobe Acrobat PDF version of this information, you can download these 3 chapters FREE.

Your Feedback

If you have a question about any of the information covered in this series, your best chance of a quick response is to post your query in the SitePoint Forums. Suggestions for improvement as well as notices of any mistakes you may find (one or two may have slipped through the cracks) are especially welcome — submit these to SitePoint Book Support.

Now that’s out of the way, let’s get our hands dirty as we learn the essentials of Flash!

Why Use Flash?

The new user can approach Flash from many different angles. Designers may well be impressed by Flash’s capabilities in the realms of interface design, aesthetics, and functionality. If you have a strong coding background, mathematical experimentation and the opportunity to learn new coding techniques may pique your interest. Regardless of which direction you approach it from, the technology offers something to every budding Flash developer.

Flash’s inherent ability to create super-compact, vector-based animations, coupled with a powerful scripting language (ActionScript), allows users to develop complex effects, transitions, and interfaces with relative ease – something that would take many more hours, or be completely impossible, using traditional HTML and DHTML coding methods.

Flash has enjoyed several incarnations since the early days before Macromedia acquired the now ubiquitous plug-in and authoring tool, and development continues today with the recent release of Flash MX 2004 Professional. The passing years have seen the use of Flash technology shift from black art to mainstream Web development practice, as each new version of the software provides users with additional capabilities, from animation, sound, and interactivity, to application server access and video inclusion.

If a complete Flash newbie were to purchase the latest copy of Flash and install it, he or she would likely be overwhelmed by the plethora of panels, drop-down menus, and user options available. Yet, after some experimentation, and a little time spent reading the manual and online tutorials, things would start to make sense. If you’re in this boat – if this is the first book you’ve purchased since your recent acquisition of Flash – congratulations! You’re in good company. If, on the other hand, you know your way around the application and its interface, and know what you want to do but are not exactly sure how to do it, then you, too, have come to the right place. Throughout this book, I’ll attempt to present methods and procedures that address the questions that are most commonly posed in online forums and newsgroups. Sure, there are thousands of examples I could show you, but the solutions I’ve included here are the pick of the crop. Once you understand how the examples in this book fit together, you’ll be able to apply them to many different instances and situations, and use them as building blocks for other Flash applications you may create.

Flash’s power springs from its dynamism and versatility. There are so many things you can do with it, from creating simple animations for inclusion in your Web applications, to building robust SQL and XML data-feeding super-applications. It can be difficult to identify a single point at which to start or stop. You could decide to create a low-bandwidth animated headline for your Website; you might choose to build the whole of your Website as a Flash application or series of Flash applications. The choice is entirely up to you. This book provides real-world examples and leading-edge techniques involving different aspects of Flash. After each example, modifications will be presented that will allow you to extend that example to suit your particular needs.

I’ll assume you’re using Flash MX or later, and that you have some understanding of the software. This book won’t walk you through the interface and tell you what it can do; instead, I expect you have a grip on the basics, and that you’re itching to start using the program to its full potential. Some of the examples in this book are specific to Flash MX 2004, demonstrating powerful techniques for getting the most out of that version in the shortest time, but the majority apply to Flash MX and above.

It’s time to buckle up and turn on the ignition. Let’s see what Flash has to offer!

Note also that you can download this chapter in pdf format if you’d prefer to read this content offline.

What’s New In Flash MX 2004?

Flash MX 2004 is a step above previous versions. Not only does it offer a plethora of enhancements and new features, but the software comes in two “flavours”: Flash MX 2004 and Flash MX Professional 2004. Your needs will determine which version is right for you. Flash MX 2004 is the ideal instrument for developing multimedia content, or adding video, audio, graphics, or data to your projects. Flash MX 2004 Professional, on the other hand, contains additional features such as forms-based programming (much like Microsoft Visual Studio), data connectors for binding XML and Web Services to your projects, and project management tools.

If you intend to create projects that contain anything more than a modicum of ActionScript, you require connection to external data sources, or want to harness the power of advanced components, then I would strongly advise you to buy Flash MX Professional 2004. The day will come – probably sooner than you expect – when you’ll need the extra horsepower it delivers. Don’t get caught short!

Flash MX 2004 Features at a Glance

Let’s take a look at the major improvements and new features offered by the 2004 releases. Those features marked (PRO) are available in the professional edition only.

ActionScript 2.0
A major object-oriented improvement to the ActionScript model, ActionScript 2.0 allows for strong typing and inheritance in accordance with the ECMA specifications. Don’t worry if these terms are new to you – we’ll discuss them in detail later.

Performance
The new version of the Flash Player has been substantially overhauled to increase playback speeds and responsiveness.

Error Reporting
The error reports generated when a Flash movie is previewed internally have been much improved in this release of the software. The reports provide more descriptive information, which makes it easier to fix show-stopping errors. See Chapter 9, Debugging for more information.

Security Model
The Flash Player security model has been improved significantly, and now provides even tighter security for your applications.

Importing
Flash developers can now import several new formats, including Adobe PDF and Adobe Illustrator 10. Flash MX 2004 also includes a Video Import Wizard to make importing video formats easier. See Chapter 6, Video Effects for details on this functionality.

Spell Checking
A fantastic new feature, spell check allows you to search text within your movies for typographical errors.

Help Panel
The Help Panel includes context-based help as well as a full ActionScript reference that updates at the click of a button with the latest content from Macromedia.

New Templates
A list of new templates designed to aid the rapid development of Flash applications is available with the 2004 release of Flash. The templates include:

  • Advertising
  • Form Applications (PRO)
  • Mobile Devices
  • Photo Slideshows
  • Presentations
  • Quiz
  • Slide Presentations (PRO)
  • Video (PRO)

To access the templates, select File > New, and click the Templates tab.

Timeline Effects
Timeline Effects allow you quickly to create editable common effects such as exploding text, blurred animation, and opacity transitions. Due to the extended API of Flash in the 2004 editions, many third-party software vendors now create these effects for use in Flash. An excellent range of third-party Timeline Effects is available from Macromedia’s online store, and includes Distort FX, Pixel FX, and Text FX, developed by Red Giant Software. These allow you to create some mind-bending visuals from within Flash.

Behaviors
Behaviors allow you to quickly add basic ActionScript commands to your movies. They can form building blocks for your code, or you can simply use them to add interactivity without getting your hands dirty with ActionScript.

To access the Behaviors Panel, select Window > Development Panels > Behaviors.

Advanced Components (PRO)
Flash MX 2004 Professional includes a new series of components that facilitate the development of complex applications.

Flash Form Presentation (PRO)
Flash Form Presentation reflects a new development system much like that of Microsoft Visual Studio. It allows for the rapid creation of, for example, contact and registration forms. See Chapter 7, Flash Forms for more.

Flash Slide Presentation (PRO)
Creating slide-based applications has never been easier, thanks to the inclusion of built-in navigation to help users move through the slides.

Data Binding and Data Connection Objects (PRO)
Flash MX 2004 Professional introduces built-in data connectors to external data sources such as Web services and XML. With the introduction of Data Binding, components such as ComboBoxes can be populated with external data relatively easily.

Source Control (PRO)
You can now easily leverage source control in your Flash projects by integrating Flash with Microsoft Visual SourceSafe. This ensures you don’t overwrite work by other team members on critical projects via the ‘Check-In/Check-Out’ methodology.

Comparing Vectors and Bitmaps

During the early days of Web design, bandwidth was always an issue – the greater the page content, and the larger the number of images, the longer the wait for the page to render in the browser.

Long download times proved to be a big turn-off for many surfers. However, as the Web evolves and high-speed connections become more commonplace in homes and workplaces, less emphasis is placed on creating super-tight pages with ultra-skinny images. Of course, it’s still best practice to write concise code, and make sure you images are as small as possible, in order to keep download times to a minimum. With Flash’s vector-based graphics system, you can consistently generate Web-optimized images and create low bandwidth applications. The beauty of creating images within Flash is that when you zoom into the movie, you don’t experience the loss of clarity or the pixellation that occurs with traditional bitmaps. This produces a crisper look and feel, as shown in Figure 1.1.

1366_ch1001
Figure 1.1. Compare bitmap and vector image file formats.

You can import traditional bitmaps into Flash, but these will obviously increase the size of the final movie. For example, if you compared a vector-based interface created within Flash to an interface built from multiple bitmaps and HTML, the Flash-developed interface file size would be dramatically lower, and the download speed significantly faster, than the bitmap-and-HTML version of the page.

Interactivity Unlimited

Flash uses an object-oriented programming language called ActionScript, which shares many themes and functions with JavaScript. As JavaScript is familiar to many Web designers, understanding the ActionScript syntax can be relatively easy. In fact, this is the case even for those without a programming background. Subsequent chapters provide a full explanation of how the application fits together, as well as the reasoning behind ActionScript code.

Designing interactive effects in Flash stumps many developers. They might have an idea of what they want to do, but they don’t know how to do it, what can be scripted, or which effects require normal timeline interaction and tweening. The major advantage of creating scripted effects is that merely altering a few variables or the way a function is referenced can have a dramatic impact upon the final movie. Creating effects with traditional methods means altering the timeline, keyframes, and tweening, and can be quite daunting – especially when you’re working with a large number of frames and layers. The techniques outlined in this book will involve scripted effects unless otherwise noted.

When a new user casts their eye over several lines of ActionScript, the typical response is a glazing over of the eyes. The sight of virtually any programming language can scare beginners away, but it’s important to remember that ActionScript isn’t difficult to understand; its learning curve is comparatively gentle. Events are triggered in three ways: buttons within the interface are clicked, certain conditions are met, or the playhead of the timeline reaches a certain frame.

While ActionScript can get very complicated, there are many ways to create quick, pleasing effects with minimal effort. Every line of ActionScript you create will help you understand further the intricacies of the language and how it can be modified to suit your needs. Every line you write will give you more confidence to undertake increasingly complex and rewarding projects.

With this in mind, let’s move on to explore ActionScript’s common terminology, the programming interface, and how it all fits together to create the effects you desire.
ActionScript Uncovered

ActionScript is an Object-Oriented Programming (OOP) language that interacts with a movie’s objects and controls the movie’s playhead. ActionScript is ECMA-262-compliant, which means it conforms to the international standard for JavaScript.

While we will examine many aspects of ActionScript, it’s beyond the scope of this publication to cover every built-in function and object. The books listed below cover most of the extended functionality of JavaScript and ActionScript, and are invaluable references that should be a part of any Flash developer’s library.

  • ActionScript: The Definitive Guide (2nd Edition, O’Reilly)
  • Professional JavaScript (2nd Edition, SAMS)

Throughout this book, I’ll explain why we’re using particular pieces of code; where appropriate, I’ll also show how similar functions can be carried out by timeline manipulation, and why it’s best practice to script them in most circumstances.

Here’s a simple example that illustrates the benefits of ActionScripting and indicates how easy it is to manipulate parts of the ActionScript to alter the final outcome.

To animate an object’s movement from point A to point B, you could create a movie clip of the object you want to move, create two key frames on the timeline, and tween between them to produce the movement. While this is a legitimate method for creating animation, you can instead script this process in a few lines of simple code.

Assume we have a movie clip named myMC. Adding the following ActionScript code to the main timeline moves the movie clip to the right if the horizontal position (_x) is less than 500:

myMC.onEnterFrame = function ()   
 {   
  if (this._x < 500)   
  {   
    this._x++;   
  }   
 };

Pretty simple, isn’t it?

The good thing about scripting animation and other effects is that the scripts can be stored within your own script library (or a shared library), ready for inclusion in your Flash applications whenever you need them. Changing the scripts to suit your needs, rather than altering nested timelines, has obvious benefits in terms of your own productivity, and in helping you develop a reference library. To change the range of motion in the above example, we could simply alter the numeric value from 500 to some other value.

Let’s take a quick look at some of the objectives ActionScript can accomplish, bearing in mind that these are just a few of its many uses. In later chapters, we’ll cover many more, including some that may surprise you.

  • Simple or complex animation effects
  • Transitional effects
  • Interactive user interfaces
  • Menu systems that cannot be produced in any other medium
  • Experimental mathematical effects
  • Simple or complex interactive games
  • Connection to databases or external files via a middle tier (ASP, ColdFusion, PHP, or Macromedia Data Connection Components)
ActionScript Dot Notation

ActionScript uses a special method to reference objects that appear on the stage and are embedded within movie clips and buttons. If you’re familiar with JavaScript, you’ll be at home with the ActionScript Dot Notation for referencing objects within your Flash movies. According to this notation, document.layer1.form1.checkbox1.value refers to the value of a checkbox within a form inside a layer contained in the current document.

If you’re not familiar with this method of referencing objects, don’t worry – it’s as straightforward as falling off a bike. You’ll soon pick it up!

There are three special keywords in ActionScript that can be used to address objects on the stage:

  • this – refers to the actual object to which the script is attached (i.e. itself)
  • _parent – refers to the movie clip that contains the object to which the script is attached
  • _root – refers to the main Flash movie, which contains the entire hierarchy of objects

In this discussion, let’s concentrate on _root. Say you create a Flash movie that contains a movie clip called Cloud, which in turn contains another movie clip called Water_Droplet_001. To find the alpha property value (opacity) of the Water_Droplet_001 clip, you could use the following ActionScript expression:

_root.Cloud.Water_Droplet_001._alpha

How does this code work? Have a look at Figure 1.2 below. Notice that the water droplets are contained within the cloud (i.e. they’re children of the parent cloud). We reference a single water droplet – for the sake of simplicity, the first water droplet (water_droplet_001) – within that cloud. The reason we use the term _root before the object is to tell Flash to start looking from the very top of the movie hierarchy within the stage.

1366_ch1002
Figure 1.2. Understand the impact of the ActionScript dot notation.

Grabbing this value of the alpha property of the Water_Droplet_001 movie clip, and storing it in a variable named Water_Droplet_001_Alpha, is as simple as this:

Water_Droplet_001_Alpha = _root.Cloud.Water_Droplet_001._alpha;

Objects placed on the canvas can have many properties controllable both from within, and outside, the objects themselves – all of which adds to the fun of experimentation and learning.

Actions Panel Unraveled

Actions are pieces of ActionScript code that perform specified functions. Functions that are commonly used to create basic actions within Flash include:

getURL
Sends the browser to an HTML page you specify

stop
Stops the playhead of the timeline

play
Starts the playhead of the timeline

gotoAndPlay, gotoAndStop
Jumps the playhead of the timeline to either a labeled frame or frame number

These core ActionScript functions are among the most common you’ll use to navigate to different parts of a movie. You may already have encountered them while dabbling in Flash 5 or later versions of the software. This really is just the tip of the iceberg when it comes to ActionScript. As you’ll see later, it offers numerous ways to increase interaction and add special effects to your work.

ActionScript is added to the stage via the Actions Panel. If you’ve ever created a scripted animation, or any effects that use these basic methods, you will have seen the Actions Panel. In this book, it will be the single most important weapon in your arsenal, so let’s go through it now to make sure you understand everything this tool places at your disposal. You can access the panel through Window > Development Panels > Actions, or by hitting F9.

1366_ch1003
Figure 1.3. The Actions Panel in Flash MX 2004 is your single most important weapon.

Figure 1.3 shows the Actions Panel with the following components indicated:

  1. Add a new item to the script window
  2. Find code
  3. Find and replace (very useful)
  4. Insert target path browser
  5. Check syntax
  6. Auto-format code (you can change formatting preferences from the Options menu)
  7. Show code hint (when at a relevant point)
  8. Options menu (useful in configuring code hinting, code colors etc.)
  9. View options (line numbers, word wrap, Esc shortcut keys)
  10. Debug options (see Chapter 9, Debugging)
  11. ActionScript reference
  12. Pin active script within Actions Panel
  13. Actions toolbox
  14. Script navigator
  15. Script pane
Actions Panel Framework

The Actions Panel doesn’t offer Expert and Normal modes in Flash MX 2004 or Flash MX 2004 Professional. In earlier versions, the Actions Panel could be run in one of these two modes, toggled to from its Options menu. In Normal mode, actions could be inserted only via the menu system; Expert Mode allowed the developer to enter actions by typing directly into the Actions Panel itself. In the 2004 editions, you can add ActionScript to the Script pane only through direct input, the Actions toolbox, or the + button above the Script pane.

If you’re still “finding your feet” when it comes to the Actions Panel, you aren’t left completely on your own. Flash’s code hinting functionality will attempt to complete your code automatically, or offer you a choice of syntax based on what you’ve already typed. For example, if you type “Math” within the Actions Panel, you’ll be presented with a list of methods that are available for the Math class, ordered alphabetically from abs to tan. You can then either select the method you require from the drop-down menu or continue typing the script yourself.

Optimizing the Actions Panel

One of the important elements of working efficiently within Flash, and decreasing the development time of scripted effects, is an efficient and comfortable working environment. Now, I’m not about to tell you to vacuum your room and polish your desk (although I have to admit that before I sit down to a scripting session, I do sort my papers out and try to clear up my workspace). But remember: a tidy environment reflects a tidy mind, and tidy code is easier to understand when you come back to it at a later date.

1366_ch1005
Figure 1.4. Get to know the important options within the Actions Panel.

There are three major options available within the Actions Panel that are great time-savers, and will aid you in your quest for coding perfection. The buttons for these are found in Figure 1.4:

  1. Show Code Hint: When you type directly into the Actions Panel and Flash suggests syntax to complete your code, you’ll note that if you don’t accept this suggestion, after a short time it will disappear from the screen. At other times, you may be happily coding away, only to have the ActionScript gremlins run in and steal thoughts from your brain – suddenly, you forget what you were typing! In either event, click this button to have the program display a code hint relative to your current position in the script.
  2. Auto Format: After heavy code editing, additions, and deletions, the comments and formatting within your code can get a little out of kilter. A simple click of the Auto Format button will format your code beautifully, based on either preset rules or custom rules you set up, as described in the next section. This is one of the most frequently clicked buttons in my copy of Flash – it’s a welcome addition to Flash MX and later versions.
  3. Check Syntax: When you’re examining the impact of a piece of script on the final movie, the last thing you want to see is an output window full of errors. To check your code for errors without either exporting the movie or viewing it within the internal Flash Player, click on the Check Syntax button (Ctrl-T, or Command-T on Mac). This will report any errors immediately, which can save a lot of time in the initial development phases.
Configuring Auto Format

Coming back to a piece of code you developed six months earlier can be a pleasant experience if your code is effectively formatted and commented; if not, it can be a veritable nightmare.

The Auto Format button helps keep your code in the best possible condition. While it doesn’t comment code for you, it does make code readable – definitely a bonus when you’re revisiting libraries of compiled code. To alter the Auto Format options to your liking, select Auto Format Options… from the Options drop-down menu in the corner of the Actions Panel. To keep your code in pristine condition, I suggest you check all the checkboxes, which will produce a similar result to that shown in Figure 1.5.

1366_ch1004
Figure 1.5. Adjust the Auto Format options to generate cleaner code.

Code Commenting

There comes a time during every project, be it large or small, when you return to a line or chunk of code and think ‘Hmm… what does that bit do again?’ There’s nothing worse than having no idea what your code does, and needing to work through it all again to make alterations or reuse it in another project. Commenting will make your code more readable, easier to navigate, and, if you work as part of a team, more easily transferred or shared via common libraries.
Note

Comments in ActionScript are not executed when a movie is running; in fact, Flash completely ignores them. They’re for your benefit, used to describe your code or temporarily disable sections of it.

As an example, here’s a snippet I include as the first line of every function I write. I save this as a text file in the ActionScript library on my hard drive so that I don’t need to retype it each time I use it. It contains a wealth of information that makes it easy for me (or any other developer) to see what the code does, what variables it will accept and/or output, and relevant revision data:

//-----------------------------    
 //Function Name: Name of Your Function    
 //Function Date: 15/09/2003    
 //Input:         Input Variables (e.g  Color Variable (String))    
 //Output:        Output Variables (e.g  Hex Color Reference)    
 //Revision Date: 28/09/2003: Added Non Numeric Error Checking    
 //-----------------------------

A double slash (//) tells Flash to ignore the remainder of a line of code. In the example above, each line of the comment begins with a double slash. You can also use this trick to temporarily disable a line of code, like so:

// var TestVar = _root.parentMovieClip.childMovieClip.value;

You can create multiline comments by starting them with /* and ending them with */. Here’s what the function description would look like using that style of comment:

/*-----------------------------    
  Function Name: Name of Your Function    
  Function Date: 15/09/2003    
  Input:         Input Variables (e.g  Color Variable (String))    
  Output:        Output Variables (e.g  Hex Color Reference)    
  Revision Date: 28/09/2003: Added Non Numeric Error Checking    
  -----------------------------*/

This style of comment can be used to “comment out” entire blocks of code, like this:

/*    
 _root.Option_Button.onPress = function ()    
 {    
  getURL ("http://www.google.com");    
 };    
 */

Taking a little extra time to comment code will save you and others time in the long run. Once you get into the habit of commenting, you’ll wonder how you ever got by without it.

ActionScript Coding Tips

There are a few key points to remember about creating functions and actions within the Actions Panel. These are by no means the be-all and end-all of best coding practices within Flash; they’re merely standards that will see you spend more time developing, and less time searching for and squashing bugs.

ActionScript is Case-Sensitive

Just like the JavaScript on which it’s based, ActionScript will not work as expected if it’s written in the wrong case. But there are some exceptions. For example, consider the following function:

function TestTrace () {    
  trace ("hello");    
 }

This function is completely error-free, and will output ‘hello’ to the Output Window when it’s called. Now, even though the function name is capitalized (TestTrace), you can call the function without the capitalization (testtrace), and Flash won’t complain:

myButon.onRollOver = function ()    
 {    
  testtrace ();    
 }

Note: In Flash MX, the ActionScript compilation routine is quite forgiving – it’s not case-sensitive. ActionScript will be treated as case-sensitive if you include #strict pragma as the first line of a script.

Just because ActionScript is forgiving with your own function and variable names, don’t expect it to do you the same favors when it comes to built-in names. These mistakes will stop your code from executing and are often the most annoying and difficult to find as you introduce more code into your project. For this reason, the best policy is to always take care to use the correct capitalization.

Externalize ActionScript

Externalizing large blocks of ActionScript is a good way to separate the elements of your project and help keep your code tidy and concise. Imagine, for example, that we have a piece of navigation code that’s 50 lines long. We could externalize it by cutting and pasting the code chunk into Notepad (Windows) or BBEdit (Macintosh), and saving it as navigation.as. We would then replace the code in the movie with this line:

#include "navigation.as"

This .as file would then be included in the SWF file at compilation time and need not be distributed with it.

Tip: To quickly export your ActionScript into an external file, select Export Script… from the Options menu within the Actions Panel.

Script Pinning

Because you can associate ActionScript actions with almost any element of a Flash movie, you may be working on one script fragment and need to refer to another somewhere else. Clicking the other element will display that other fragment; if you need to return to the fragment you were working on, you could easily lose your place.

To help developers avoid confusion while jumping between multiple script fragments, Macromedia has provided script pinning. Simply click the Pin Script button in the Actions Panel, and Flash will keep the currently displayed script fragment open in a tab along the bottom of the Actions Pane. You can then navigate to another element to view its script without fear of losing your place in the original script – simply click the tab to switch back to the pinned script whenever you need to. You can even pin multiple script fragments when the situation calls for it.

Note: Flash MX 2004 introduces an extra pane in the Actions Panel – the script navigator pane. Located just below the Actions toolbox, this new pane allows easy navigation through all the code in a movie.

Lift and Lock

Actions can be added to the timeline within keyframes, or assigned to objects on the stage. Regardless which type of action you’re creating, however, it’s best practice to create a new layer, give it a meaningful name such as ‘ActionScript’, and lock the layer before placing your ActionScript in it. This way, you can easily see the objects containing ActionScript and navigate to them without having to open the Movie Explorer.
Naming Conventions

When you write code, create functions, or name layers and folders, there is a set of best practices that you should try to implement. Some of these are common sense; others are not so obvious. None of these conventions is essential, but by following these simple guidelines and other suggestions in this chapter, you should be able to organize your Flash projects successfully.

Do

  • create filenames that relate to the purpose or goals of the Flash project
  • create names for functions and variables that indicate their roles in the project
  • use underscores to separate words; avoid hyphens
  • be consistent in your application of the naming system you decide to use

Do Not

  • use acronyms that make little or no sense
  • shorten filenames
  • create function, file, or variable names that require a Masters degree in Particle Science to decrypt
  • use spaces or merge words together

The Timeline, Simplified

In our reality, time can only go forward (though some may argue otherwise!); the same is not true in Flash. The playhead within the timeline can move forward and backward – it can even jump frames.

The Flash timeline is integral to creating effects, and all Flash movies use the timeline, even if only for the first frame. The introduction of Timeline Effects in Flash MX 2004 has made it very easy to create rapid animations and transitional effects within your projects. With basic ActionScript, you can start the playhead, play an animation, and send the playhead back to the beginning of the timeline to play again. And, with only slight modification, you can add an auto-incrementing counter to either conditionally jump to another point on the timeline or return to the start of the timeline. It’s simple to create basic effects and build them up into something extraordinary.

Timeline Effects also make it easier to develop complex effects that are transferable to other projects or collaborators. Indeed, this concept of scalability should always be considered at the start of a project. Before you begin, ask yourself, “Will I easily be able to use this effect again in the same movie, or another project, without extensive recoding?” If the answer is no, you need to identify ways to make it scalable.

The easiest path to scalability is to invest a little time in scripting common tasks. If you can animate an object using four lines of ActionScript that represent a reusable function or snippet, go for it! This approach makes for easier maintenance than a script containing multiple duplicated, nested movie clips in which the variables may clash.

Ask yourself these questions before creating a new effect or starting any project:

  1. Will multiple effects occur on the stage at the same time?
  2. Will I use the same effect more than once in the movie?
  3. Can I script the effect I wish to create?
  4. Can I make the effect easily portable between projects?
  5. Can I easily add new functionality to the effect?
  6. If the clients or I don’t like the effect, can I easily tweak it?

You can create complex effects using the timeline – in fact, before the release of Flash 5 and later versions, this was the only way to do so. Even today, most of the animation effects we see rely on timeline tweening between frames to create animation, movement, and opacity fading. The combination of Timeline Effects and ActionScript can be a powerful one, but this approach also has a technical advantage. Effects developed this way are more ‘tweakable;’ changing a few settings here and there impacts the final product considerably in very little time.

The importance of the timeline should not be underestimated. Every single object, from layers to movie clips, is present within the timeline when it’s added to the stage. Take some time to become familiar with the best practice principles for working with the timeline.

Label Me Up

After a weekend or holiday, how long does it take you to come to terms with the Flash projects you left behind? Organization is the key to minimizing this “re-familiarization” time. There’s no excuse for sloppy code or disorganized Flash projects. Invest a little extra time at the start of a project, add elements with care, and you’ll reap the rewards when you return to it after time away or hand it over to your colleagues.

I advocate the creation of a layer named ‘Labels’ to hold commentary, conditions, and pointers as to what’s happening at each step on the timeline. This process is as simple as selecting a frame from the timeline, and adding a Frame Label within the Property Inspector. Maintaining these rolling labels allows you to see what’s happening within your movies – you can even add small notes, for example, to remind yourself that code requires alteration, or graphics need to be swapped out.

Note: Flash MX 2004 allows you to efficiently alter the frame label type. To change a name, label, or anchor’s representation within the timeline, simply click the drop-down box that appears beneath the frame label within the Property Inspector.

Adding a Labels layer keeps this information separate and helps you organize your thoughts regarding timeline planning.

Organize Your Layers

In Flash version 5 and earlier, users had the ability to organize work into distinct layers within the timeline. This facility was extremely helpful for separating out design components within the stage. A little planning and organization of these layers can benefit you both during the initial development process and when revisiting a project at a later date.

In Flash MX and Flash MX 2004, you can organize these layers into discrete folders. Let me show you how this seemingly small enhancement can improve your workflow.

Let’s say you’ve been working for a while on a project that has many movie clips, buttons, and bitmaps on the stage. You’re using many layers, though they’re not organized into any particular format, and you’re scrolling up and down the timeline window to access them as you go. To make matters worse, the project is growing more complicated, which means more layers and even more scrolling. Fear not – this is all about to change! Figure 1.6 shows how you can create and organize folders into discrete compartments, placing relevant layers within each. When you finish editing a folder, just click the arrow next to it to roll it up and give yourself more space within the timeline. As the projects you undertake become more involved and larger, the improved efficiency you can gain from this approach will become self-evident.

In adding components to a project, I usually start with a standard framework. I have a folder containing two layers – one for ActionScript, the other for labels. I have another folder for Animations, which is then subdivided into relevant sections, and a folder for static imagery. Obviously, you can change this structure to suit your development needs and personal preferences.

1366_ch1007
Figure 1.6. Organize folders and layers with ease in Flash MX and Flash MX 2004.

Timeline Effects (New in Flash MX 2004)

New within Flash MX 2004 is a much-anticipated addition to the arsenal of experienced programmers and non-programmers alike: Timeline Effects. These are available from the Insert menu after you’ve selected an object from the stage. You can access them at: Insert > Timeline Effects > Effect.

There are several effect categories, each containing many possible choices:

  • Blur
  • Expand
  • Explode
  • Fade In
  • Fade Out
  • Fly In
  • Fly Out
  • Grow
  • Shrink
  • Spin Left
  • Spin Right
  • Wipe In
  • Wipe Out

We’ll cover these in depth, and see how they can be used to create engaging effects, in Chapter 4, Text Effects.

Traditionally, to fade the opacity of an object from completely transparent to completely opaque, I would access the timeline and tween between two instances of a movie clip, altering the alpha values accordingly. Though functional, this technique can be quite time-consuming and fiddly, especially if you’re looking to build an effect with multiple movie clips fading in, in a stepped manner, to produce a blur. The addition of Timeline Effects provides developers a large degree of control over setup parameters. With so many of these at your disposal, it’s quick and easy to create compositions for yourself or for presentation to clients.

Figure 1.7 shows that many properties are available within the Fade In command. Straight out of the box, the effect can be applied and previewed within a matter of seconds, shaving considerable time off the old techniques, especially if you’re using multiple iterations of the same effect. Combining Timeline Effects often produces unexpected yet pleasing results. The key to creative success is, as always, to experiment until you’re happy with the outcome.

1366_ch1006
Figure 1.7. Edit the Fade In Timeline Effects parameters within Flash MX 2004.

Wrapping Up the Basics

We’ve covered the basics of ActionScript and the Timeline, and discussed best practices for both. Now it’s time to apply these tactics to create stunning effects that are appealing, easily transferable among projects, and fun to explore and expand. In the next few chapters, we’ll cover a range of subjects, with examples, suggestions, and explanations of techniques that will prove invaluable in your day-to-day Flash projects.