Macromedia Flash MX Action Script Tutorial
Macromedia Flash MX Action Script Tutorial
CD-ROM Included
Source files and artwork for chapter projects
Doug Sahlin
Doug Sahlin
Best-Selling Books Digital Downloads e-Books Answer Networks e-Newsletters Branded Web Sites e-Learning
Flash MX ActionScript For Designers Published by Wiley Publishing, Inc. 909 Third Avenue New York, NY 10022
www.wiley.com
Copyright 2002 by Wiley Publishing, Inc., Indianapolis, Indiana Library of Congress Control Number: 2002106038 ISBN: 0-7645-3687-7 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1O/QR/QX/QS/IN Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4744. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-Mail: [email protected]. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Cataloging-in-Publication Data Trademarks: Wiley and related trade dress are registered trademarks of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permission. FreeHand 10 Copyright 1995-2000. Macromedia, Inc. 600 Townsend Street, San Francisco, CA 94103 USA. All Rights Reserved. Macromedia, FreeHand, Flash and ActionScript are trademarks or registered trademarks of Macromedia, Inc. in the United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
is a trademark of Wiley Publishing, Inc.
Credits
Acquisitions Editor Tom Heine Project Editor Andrea C. Boucher Technical Editor Kyle Bowen Editorial Manager Rev Mengle Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Bob Ipsen Executive Editorial Director Mary Bednarek Project Coordinator Regina Snyder Graphics and Production Specialists Beth Brooks, Joyce Haughey, Gabriele McCann, Jeremey Unger Quality Control Technicians Laura Albert, Andy Hollandbeck, Susan Mortiz, Carl Pierce, Charles Spencer Permissions Editor Laura Moss Media Development Specialist Marisa Pearman, Travis Silvers Proofreading and Indexing TECHBOOKS Production Services
Preface
lash MX is the predominant choice for Web designers who want to create interactive designs for their clients. With more features than ever before, Flash is a total Web publishing solution. With Flash MX, you can now include video in your designs. The total number of available actions has more than doubled with this major Flash upgrade. The Flash Player is included with every computer operating system and the most popular Web browsers. With a user base of 442,692,972 installed Flash Players as of May 2, 2002, its no wonder Web designers and developers using Flash practice the fine art of one-upmanship for their clients. With such a large a user-base, all Web designers need to know how to use Flash if they are to get their fair share of this immense pie. Flash MX ActionScript For Designers will show you how to harness the power of ActionScript. If youve wanted to come up to speed with ActionScript but the sheer volume of available actions caused you to stick with the tried-and-true Flash animation methods, youll find the answers to many of your questions in this book. I show you how to use the basic actions to control the flow of your design. Even though ActionScript can be daunting, the basics of ActionScripts Object Oriented Programming are presented in easy-to-understand laymans terms. The primary focus of this book is to show you how to use ActionScript to add excitement and diversity to your designs. If youve wanted to take the next step and push the envelope with ActionScript, you have the right book in your hands. Throughout this book youll find concise examples of ActionScript at work examples that you can put to use in your daily work. In addition, many chapters feature a project that shows you how to use the material to create a finished object with ActionScript.
vi
be exposed to concepts and theory that give you a firm background of what you can and cannot do with ActionScript. And as you will find out, the cannots are limited largely by your imagination. If youre ready to combine your artistic talent and imagination with the power of ActionScript, youll find many things to whet your appetite in this book. If youve ever wondered how the hotshot designers make their magic with Flash, youll find some of the answers in this book.
Preface
vii
Appendixes
The final section of the book is devoted to three appendixes: Appendix A: Whats on the CD-ROM details the contents of the CD, from the author-created materials to the applications and software available for your use as you work your way through the book. Appendix B: Flash Resources is a roadmap to sources of Flash information on the Internet. In this section youll find the URLs to sites where you can find additional tutorials and examples of ActionScript at work. Appendix C: Flash Inspiration is a list of Web sites designed by ActionScript gurus. If youve ever been at a loss for a new idea, a quick trip to one of the sites in this section will get your creative juices flowing.
viii
Cross-Reference icons point to additional information about a topic, which you can find in other sections of the book. A Note icon contains additional information about the topic of discussion. In fact, you can use notes and tips to locate sections of interest if youre in a hurry. The On the CD-ROM icon is your signpost to the raw materials for a chapter project. When you see this icon, youll be directed to a folder and a file that contains the raw material for the project youll finish. When you see a Tip icon, youll find information that will streamline your work with ActionScript, as well as handy shortcuts to speed up your production.
Note
On the CD-ROM
Tip
In addition to the icons listed previously, the following typographical conventions are used throughout the book: Code examples appear in a courier font. Actions are designated as follows: goto. When you are required to enter code in an ActionScript text box, the required entry will be designated as bold text. Youll see many examples of ActionScript code shown in a listing. The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
Acknowledgments
ven though one persons name appears on the cover of this book, a project of this magnitude would not be possible without the concerted effort of many. Thanks to the fine folks at Wiley Publishing for giving me the opportunity to bring this project to fruition. Special thanks to Acquisitions Editor Tom Heine for working out the fine points of the concept and content. As always, thanks to the lovely and talented Margot Maley Hutchinson for ironing out the fine print in the contract. Youre a gem, Margot. Speaking of gems, another young lady played a large part in this production. Kudos to the effervescent and ebullient Andrea Boucher, Project Editor extraordinaire, and just another example of why blonde-haired people will soon rule the universe. Thank you for your steadfast, guiding hand and kind words of encouragement when the going got tough. Thanks to Marisa Pearman, Wiley Media Development Specialist, for employing her magic on the creation of this books CD-ROM. Many thanks to the vendors who contributed software for this CD-ROM. Special thanks to the Macromedia Flash MX development team and all of the creative people at Macromedia. Thank you for your continued support of authors and for producing the best Web design software on the planet. Special thanks to the wild and wacky members of the Flash community, people who survive on but a few hours sleep and offer support beyond measure to fellow Flash users and authors. You people are truly amazing. As always, thanks to my mentors, friends, and family, especially you, Ted and Karen. Congratulations to Karen and Shel on their recent marriage. And thank you Karen and Shel for the wonderful memories of St. John. Special thanks to a lovely lady who will live on always in my memory: my dear mother Inez. She provided the wind in my sails when I was a young boy and used her gentle wisdom to guide me, and yet at the same time allowed me to become the individual that I am. I wish you were here to share this with me.
Contents at a Glance
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Part IV: Building Additional Design Elements for Your Movie . . . . 295
CHAPTER 15: Building Web Site Elements with ActionScript CHAPTER 16: Creating Flash Eye Candy . . . . . . . . . . . . CHAPTER 17: Integrating Flash with HTML . . . . . . . . . . Appendix A: Whats on the CD-ROM . . . . . . . . . . . . . . Appendix B: Flash Resources . . . . . . . . . . . . . . . . . . Appendix C: Flash Inspiration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 315 339 357 363 369
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
xii
Changing your viewing options . . . . . . . Using the Actions panel Options menu . . . Creating ActionScript in expert mode . . . Using the Actions panel context menu . . . Understanding ActionScript conventions . Understanding Symbol Types . . . . . . . . . . . About the button symbol . . . . . . . . . . . About the graphics symbol . . . . . . . . . . About the movie clip symbol . . . . . . . . . About the component symbol . . . . . . . . About the Document Library . . . . . . . . . . . . Chapter Project: Creating Your First ActionScript
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
35 35 36 37 37 42 42 42 43 43 43 44
63
. . . . . . . . . . . . . . . 66 66 69 70 70 72 72 73 74 74 76 76 76 77 77
. . . . . . . . . . . . . . 79
Contents
xiii
xiv
Loading a Different-Sized Movie into a Target . . . Creating a target movie clip . . . . . . . . . . Loading a movie into a target . . . . . . . . . Communicating between Timelines . . . . . . . . Demystifying Targets and Paths . . . . . . . . . . . Using Absolute mode . . . . . . . . . . . . . Using Relative mode . . . . . . . . . . . . . . Introducing the User-Defined Component . . . . . Chapter Project: Creating an Organizational Chart Beginning the design . . . . . . . . . . . . . . Creating the ActionScript . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
125 125 127 129 130 131 131 132 135 136 137
165
Contents
xv
Modifying an object by addressing its target path . . . Getting an objects properties . . . . . . . . . . . . . . Using the Color Object . . . . . . . . . . . . . . . . . . . . . . Creating a Color object . . . . . . . . . . . . . . . . . . Modifying an objects color . . . . . . . . . . . . . . . . Using the Key Object . . . . . . . . . . . . . . . . . . . . . . . Duplicating an Object Using the duplicateMovieClip Action Chapter Project: Creating an Interactive Animation . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
xvi
. . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 232 235 237 238 239 240 241 245 245 246 247 249 251
Building Tooltips . . . . . . . . . . . . . . . . . . . . Creating the tooltips . . . . . . . . . . . . . . . Creating the tooltip functions . . . . . . . . . Programming the buttons . . . . . . . . . . . . Creating Drag-and-Drop Elements . . . . . . . . . . Creating a drag-and-drop window . . . . . . . Closing a window . . . . . . . . . . . . . . . . . Creating a User Customizable Interface . . . . . . . Telling Time with ActionScript . . . . . . . . . . . . Creating a Date object . . . . . . . . . . . . . . Displaying the current date . . . . . . . . . . . Displaying the current time . . . . . . . . . . Using the ScrollBar Component . . . . . . . . . . . . Chapter Project: Creating a Moving Navigation Bar
. . . . . . . . . . . . . . . . 283
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 285 286 287 288
Testing Your Design . . . . . . . . . . . . . . . . . Using the Debugger . . . . . . . . . . . . . . . . . Watching a variable . . . . . . . . . . . . . Displaying a list of movie objects . . . . . Displaying a list of variables in the movie .
Contents
xvii
Using the Trace Action . . . . . . . . . . . . Stopping the Movie with Breakpoints . . . Setting a breakpoint . . . . . . . . . . Debugging a movie with breakpoints Tracking ActionScript with Comments . . . Using the Movie Explorer . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
295
. . . . . . . . . 298 299 302 306 306 308 308 310 312
xviii
Appendix A: Whats on the CD-ROM . . . . . . . . . . . . . . . . . . . 357 Appendix B: Flash Resources . . . . . . . . . . . . . . . . . . . . . . . 363 Appendix C: Flash Inspiration . . . . . . . . . . . . . . . . . . . . . . . 369 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 End-User License Agreement . . . . . . . . . . . . . . . . . . . . . . . . . 389
I
In This Part
Chapter 1 Introducing ActionScript for Designers Chapter 2 Delving into Your ActionScript Toolkit Chapter 3 Planning Your ActionScript Movie
C H A P T E R
In This Chapter
Understanding why designers need ActionScript Decoding objectoriented scripting Understanding how ActionScript works Using ActionScript as a design element Figuring out when to use ActionScript
In this chapter, you learn the benefits of using ActionScript and when you should use ActionScript, as well as how ActionScript works both as a scripting language and a design element.
In Flash MX, there is an additional Actions book called Index. Instead of blindly plodding through each book searching for the right action, the Index book organizes every action alphabetically. In addition, there is also a Reference panel within the Actions panel that tells you what each action does and shows you the correct syntax for every action.
Note
CrossReference
If any of your clients have a need for a Flash movie that needs frequent updating, you can use ActionScript to load text, images, and movies externally. When the site needs updating, you dont need to create a new movie just refresh the text, image, or movies, upload the new content to the Web site, and your client is good to go. Your client need not know you used ActionScript to take the drudgery out of this task. Your client will appreciate the quick turnaround and pay you what youre worth. You can write your ActionScript in a manner that makes it possible for you to reuse your best effects in another Flash movie. You create a movie clip with the effects you want to replicate in another movie. Then all you need to do is use the Flash Open As Library command, drag the movie clip into the current document, and youre ready to go.
CrossReference
Flash ActionScript also has an item you can use to create programmable objects. If youre familiar with Flash 5, you may recall the smart clip, which in essence is a movie clip with programmable parameters. In Flash MX, you have more versatility with the next generation of the smart clip known as a user-defined component. Userdefined components are another item you can use to streamline your work. If you work with other designers, all they need to do is modify the parameters of your component to use it. You can also use this little gem for a movie that needs frequent updating. If, for example, you create an e-commerce site, you can create a component to store variables that change often, such as the price of an object. When it comes time to update the product, you merely modify the parameters in your component and republish the document.
CrossReference
ActionScript also has an object called an array. An array is like a file cabinet filled with information. You can think of an array as a super-charged variable; instead of creating 20 variables to store product names, you create one array with 20 elements that stores this information. Then instead of having to remember the names of twenty variables, you remember the name of one array and the element number that houses the information. You can use arrays to store items like product names, prices, and descriptions to name a few.
For information on working with the Color object, refer to Chapter 9. To learn how to work with the Date object, see Chapter 12.
One ActionScript element designers find invaluable is the TextField object. If youve ever designed a static HTML document with lots of text, you have two choices: a standard page where the menu disappears as user scrolls through the text, or a frames site where the menu stays in place as the text is scrolled, but when the user clicks another menu button, a new page must load, disrupting the flow of information. Using the TextField object, you can create a seamless experience for the user by constraining the text to a small box and providing buttons for the user to scroll forwards or backwards while all of the navigation elements stay in place.
CrossReference
One of Flashs strong suits has always been the ability to add sound to a production. With ActionScript, you can take sound to the next level. You can design a movie that gives the user the ability to choose which sound plays while viewing your production. Add the ActionScript Sound object to the mix, and you give the user the ability to control the volume of the sound and control the balance of the sound between speakers.
CrossReference
You learn how to create movie clips and import video files in Chapter 5.
When you put your mind to it, the uses of ActionScript are potentially limitless. Instead of worrying about the lines and lines of code used to create some effects, follow the various tutorials in this book and use them in your own productions. As you become more conversant with ActionScript, let your right brain ramble, daydream, and come up with ideas youd like to incorporate in your designs. After your inspiration strikes, use ActionScript to bring it to life on the Word Wide Web or within a CD-ROM production. By stretching the ActionScript envelope, you can expand your creativity in ways you never thought possible.
You apply ActionScript to the aforementioned objects, and you also use ActionScript objects to get the job done. This may sound redundant, but it isnt. The ActionScript objects you use and the ensuing code you create make certain things happen. For example, if you want to modify a sound, you use the Sound object. If you want to retrieve the date and time from the host computer playing the published Flash movie, you use the Date object. Each object has methods that achieve certain results. For example, the Sound object has a method called setVolume, which, as the title suggests, is used to control the volume of a sound. Some objects also have properties. The Sound object has a property called duration that returns the amount of milliseconds the sound has been playing. You also find objects that have events, which you can use as a trigger for another action. The Sound object has an event called onSoundComplete. An example of a use for this property would be advancing to another frame once a descriptive narration has finished playing.
} function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf(#)!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } //--> </script>
If you examine the ActionScript in Listing 1-2, you see another important ActionScript element: the event. The first line of code in Listing 1-2 reads on(Release). The code following the Release event occurs when the user releases the mouse button. Events for buttons are known as mouse events; events for movie clips are called clip events. An event is known as a code handler. In other words, the code is handled (executed) when the event occurs. For example, the code on(Release) gotoAndPlay (2) instructs Flash to go to frame 2 and play the frame when the user releases the mouse button. When you create a movie clip, you are creating an object that has its own timeline. A movie clip is a symbol stored in the document Library. When you create an instance of a symbol on Stage, you are creating an entity with its own timeline. When you create an action from the base timeline to transform the movie clip instance, you need to specify a path so that Flash knows where to find the movie clip. A path is similar to a URL address that instructs a Web browser where a linked page is located. An ActionScript path references the timeline, the instance name of the movie clip, and the individual part of the movie clip you want Flash to access when an event occurs, for example, an individual frame in the movie clip. In essence, you are supplying Flash with a path to the target, which is the named instance of a movie clip.
CrossReference
10
You also need to reference the path to a variable you want Flash to read when an event occurs. For example, you may have a variable stored in a movie clip or perhaps in a user-defined component. Again, you must supply the proper path in order for Flash to know where the variable you want read is stored. You can also think of a path as the Flash equivalent of a Zip code. Fortunately, you dont have to type in each and every path when creating ActionScript. Flash stores the path to every named instance of a movie clip in a document within the Insert Target Path dialog box shown in Figure 1-1.
Figure 1-1: You insert target paths in your ActionScript from this dialog box.
With the most basic actions, you can control the flow of a movie, telling Flash which frame to go to when a user interacts with the movie. You can also use basic actions to load content upon demand. You can specify to load a movie, load variables, or load a JPEG image with ActionScript. You structure your ActionScript in a manner that Flash executes the desired action when the event triggered by the user occurs. You can use other actions to change the properties of an object. For example, you can change the color of an object, move an object to a different position, change an objects opacity, and much more depending upon the actions you add to your script. Figure 1-2 shows an example of ActionScript at work. The figure in the left pane is the movie clip as originally created; the figure in the right pane has undergone a makeover through the magic of ActionScript.
Figure 1-2: You can modify the physical characteristics of an object with ActionScript.
11
CrossReference
Another powerful feature of ActionScript you can use is decision making. Thats right, you can create ActionScript that determines what happens next based on user input or a change in one or more of an objects properties. A line of ActionScript that makes a decision based on an outcome is known in programmer speak as a conditional statement. The crux of a conditional statement can be summed up as follows: If these conditions are present, then this event happens. You can use a conditional statement to determine what happens next in your movie. Listing 1-3 shows an ActionScript that adds a zero in front of a variable named seconds if the variables value is less than 10.
Another powerful element you can use in your ActionScript designs is the loop. With a loop, you can repeat an action a given number of times. Instead of rewriting the code you want to occur over and over, you simply create a loop that tells Flash how many times you want to code within the loop to execute. You can use loops to duplicate and move a movie clip. You can also use a loop to display the elements in an array. Figure 1-3 shows the result of a loop used to create a background of a moving starfields.
Figure 1-3: You use an ActionScript loop to repeat code a given number of times.
12
CrossReference
Another great use for ActionScript is creating interactive buttons. Youve probably created rollover buttons for your HTML designs. However, with ActionScript, you can take a rollover button to the next level. You can create ActionScript that makes a tooltip appear when a user lingers over a button, as shown in Figure 1-5. You can create ActionScript to play a small movie when the user rolls a mouse over the button.
CrossReference
In Chapter 12, I show you how to write ActionScript code for tooltips.
13
Figure 1-5: With a bit of ActionScript code, you can create useful elements for your designs.
You can also use ActionScript to create a modular interface. By creating a base movie with a few navigation buttons and a pop-up menu, you have the basis for many Flash productions. Using ActionScript components such as the user-defined component, you can change the button text when using the menu for a different production. If youre really adventurous, you can use ActionScript to add eye candy to your designs. With a few lines of code, you can achieve stunning effects like mouse trails, motion trails, and animated backgrounds. If your design calls for an animated background, its fairly easy to achieve with ActionScript. Figure 1-6 shows a motion trail effect you learn to create in Chapter 16.
Figure 1-6: If you need eye candy for your Flash design, ActionScript is the answer.
14
ActionScript is also useful when you want to add bells and whistles to your design. Using the Date object, its possible to incorporate the date and time to any movie you design. If you create all the code for your online clock in an individual movie clip, your Flash timepiece is modular; you can use it in other movies. You learn how to create modular ActionScript in Chapter 6. If you design Flash movies for online merchants, you can use ActionScript to change the properties of the objects they sell. For example, you can use the Color object to modify the color of a ball cap, giving the user the ability to preview the product in available colors before purchase. You can also use ActionScript to create online forms and transmit the results of the form to the merchant. Figure 1-7 shows an example of an online Flash form. By combining Flash design elements with ActionScript and your own creativity, you can escape the humdrum forms that permeate HTML pages.
CrossReference
You can also integrate Flash movies with your HTML designs. If you have a client who wants a bit of Flash magic but isnt willing to cough up the coin for a fullfledged Flash design, you can create a compelling Flash intro that links to the sites home page. You can also create animated banners with Flash. A banner animated with Flash packs more punch than a traditional Animated GIF. With Flash you can create realistic motion instead of frame based animation, and you can add ActionScript elements such as programmable buttons to link the banner to another URL, or another part of the site. Figure 1-8 shows an animated Flash banner integrated with a static HTML page.
15
Figure 1-8: Banners animated with Flash add interest to static HTML sites.
16
17
Does your design involve a spoken narrative that must be coordinated with other content? If the answer to this question is yes, you need the onSoundComplete method of the Sound object to trigger the next event upon termination of the narrative. After you decide to create an ActionScript movie, which items or keyframes will you need to create code for? After youve answered these questions (and any you may have come up with on your own), youre ready to begin planning your ActionScript movie. Every designer has a different way of planning. In Chapter 3, I offer a few suggestions that have worked for me.
Note
This list of questions is not all inclusive. You need to consider your specific situation, the actual content for your movie, and your clients requirements. After youve worked with ActionScript for a while, you know what other questions you need answered before beginning a new design project.
After you answer these questions, you may find that you dont know each and every action required to create the design. Thats one of the beauties of ActionScript you dont need to know it all, just enough to get the job done. When you run across an action you dont know or understand, refer to this book for the answer. Unfortunately, a detailed treatise and tutorial for each and every action in the Actions panel (there are approximately 800 actions in all, but whos counting) is beyond the scope of this book. If you need an action not covered in this book, refer to the Flash MX ActionScript Reference Guide that was shipped with your software.
Tip
If you need to use an action youre not familiar with, you can also refer to the Reference panel from within Flash. Open the Actions panel and then click the icon that looks like a book with a question mark on its cover. After clicking the icon, Flash opens the Reference panel, which is a duplicate of every book in the Actions panel. Open a book, click the action you need to know about and Flash displays a description of the action along with required formatting syntax.
Designer Notes
In this chapter, you received your first taste of what ActionScript is and the power it can add to your designs. You also learned why designers need to know how to create ActionScript. In addition, you got a preview of the type of effects you can create with ActionScript as well as when you need to add ActionScript to your design. You also obtained an understanding of how ActionScript works. In the next chapter, you get your first look at the building blocks of ActionScript and also create your first ActionScript.
C H A P T E R
In This Chapter
Exploring the Actions panel Essential actions for designers Adding actions to your documents Deciphering symbol types Adding symbols to the document Library Chapter project: Creating your first ActionScript
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the
20
path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
Figure 2-1: You add actions to a document with the Actions panel.
The Actions panel is divided into two panes. The pane on the left houses all the action books. Each book is a group of similar actions that perform like tasks. For example, the Movie Control book contains actions you use to control the flow of a movie: stopping on a frame when desired, going to a frame, playing a frame, and so on. As the title so aptly describes, the actions in this book control the flow of a movie.
21
The right pane of the Actions panel is called the Script pane. When you add an action to a keyframe or object, the code appears in this pane. As you push the ActionScript envelope, you often end up with several lines of code in the Script pane, more than can be viewed within the window. When this happens, you can use the up and down arrows to navigate to a specific line of code. You also have several icons scattered about the perimeter of the Actions panel. You use these to access various features of the Actions panel. In upcoming sections you learn what each of these icons is used for and how theyll simplify your life as an ActionScript designer.
22
CrossReference
Actions book
Figure 2-2: You use actions from the Actions book to create ActionScript.
When you open an individual book, each action in the book is designated by a circular icon with an angled arrow and the actions title. Shown in Figure 2-3 are all the actions in the Movie Control book. The following sections details the individual books within the Actions book.
23
In Chapter 7 you learn to use actions from this book to break large productions into manageable pieces that load quickly into the users browser.
24
CrossReference
In Chapter 12 you learn how to use actions from this book to create interactive elements for interfaces.
You use other actions from this book to repeat selected lines of code, or as programmers would say, loop them. Depending on the effect you want to achieve, or the task youre asking Flash to accomplish, you can create loops that last for a predetermined number of cycles or loops that continue while a certain condition is true.
CrossReference
25
equation to see if a condition is true or false. For example, if you want to keep a moving object within the boundaries of the Stage, you compare the current position of the object with the boundaries of the Stage. You can use the logical operators to compare text objects, affectionately known to programmers as strings. You can use logical operators to in a quiz to compare a users answer with the correct answer.
CrossReference
You find information about the Logical, Comparison, and Arithmetic Operators in Chapter 8.
For more information on selected actions from the Functions book, see Chapter 8.
26
For example, the Color object has a method for changing the color of an object; the Sound object has a method for controlling the volume of a sound. Other objects have properties; the Sound object has properties for measuring the length of a sound clip and for how long a sound clip has been playing. Other objects have events that can be used in your ActionScript. The Sound object has an event called onSoundComplete that you use to trigger other actions in your movie when a sound stops playing. The different objects in this book are referred to in various projects and tutorials throughout the course of this book.
The Internet sometimes lags behind designers and programmers; therefore, you may find that many potential viewers dont have the latest Flash Player. If you publish a movie with the latest actions from Flash MX, it may not play properly on earlier Flash Players. To avoid this problem, publish the movie for the version of the Flash Player that you anticipate is in use by the majority of your intended audience. Before you create the movie, adjust the publish settings for the desired version of Flash. After you do this, any actions that will not work with your publish settings are highlighted in yellow and should not be used.
27
The first step in creating any ActionScript is to open the Actions panel. The default position of the Actions panel is directly below the Stage. You open the panel by clicking the right pointing arrow or by clicking the panels title. If, as a designer, you decided to use the Designer panel layout as supplied by Macromedia, you can do so by choosing WindowPanel Sets and then choosing the set for your desktop size. However, when you use one of the Designer panel sets, the Actions panel is hidden. Choose WindowActions, and Flash opens the panel, displaying it as a floating window (see Figure 2-5). Why the Flash programmers decided to hide the Actions panel for designers is a mystery. Perhaps they realize what a powerful combination a creative designer and the Actions panel is and decided to protect their left-brained developer brethren by hiding the panel.
28
Actions panel
Figure 2-5: The Actions panel is displayed in a floating window with the Designer panel layout.
Tip
If you use ActionScript a lot, its convenient to have the Actions panel available at all times. You may find that there are other panels you use frequently in conjunction with the Actions panel. You can begin with the default panel set or one of the Developer panel sets if you prefer to have the Actions panel docked at the bottom of the workspace with the Property inspector and Reference panel. You can then open and dock the panels you use frequently to create a panel layout that suits your working preference. When you have the workspace just the way you want it, choose WindowSave Panel Layout to open the Save Panel Layout dialog box. Enter a name for your layout, click OK, and your panel layout is added to the Panel Sets menu.
Working in modes
You have two methods of working in the Actions panel: normal mode and expert mode. In normal mode, Flash takes care of all of your formatting you can be assured that the code you create will be formatted correctly and in the right syntax.
29
When you work in expert mode, Flash turns off all the warning messages and you can enter code by typing in the Script pane, just like youd enter text into a word processing program. (More on syntax and expert mode in the upcoming section Creating ActionScript in expert mode.)
30
Figure 2-7: You choose the parameters for an action using parameter text boxes.
As you can see, you can choose the parameters for this action by clicking radio boxes or making choices from drop-down menus. Other actions require you to add information to a parameter text box, such as the contents of a variable or array. Parameter text boxes are discussed in detail as they relate to specific actions throughout this book. Many of the actions you use are simple instructions to the Flash Player, such as stop or play. When you add an action like this to your script, the Flash Player knows exactly what to do and no further instructions are needed. When you add an action of this type to your script, parameter text boxes are not needed or displayed.
31
32
Find button Find and Replace button Figure 2-8: You use the Script window to navigate to other scripts in the same keyframe.
Pinning a script
When you fine-tune and work the bugs out of your ActionScript, its often necessary to view the properties of other objects while using an ActionScript in a different keyframe for reference. Click the Pin Current Script button, and Flash locks the current script in the Script window while you navigate to other frames or view different objects. Click the Pin Current Script button again to unlock the script.
33
To find text in a script: 1. Select the keyframe or object the containing the script that contains the text you want to find and open the Actions panel. 2. Click the Find button to open the Find dialog box. Alternately, choose OptionsFind. 3. In the Find What field, enter the text you want to locate. To match the case you enter, click the Match Case checkbox. 4. Click the Find Next button, and Flash locates the first instance of the text and highlights the line of code it appears in. 5. To find the next instance of your query, click Find Next; otherwise, click Close to exit the dialog box. The Actions panel has another useful tool that allows you to find and replace text. This feature comes in handy when you copy code from another object, keyframe, or movie and just need to make minor modifications, such as changing the name of a variable. To find and replace text in a script: 1. Select the keyframe or object containing the script with the text you want to replace and open the Actions panel. 2. Click the Find and Replace button to open the Replace dialog box. Alternately, choose OptionsFind and Replace. 3. In the Find What field, enter the text you want to replace. 4. In the Replace field, enter the new text and do one of the following: To review each instance of your query, click the Find Next button. If you want to replace the text Flash locates, click Replace. To replace all instances of your query without review, click Replace All. 5. Click Close to exit the dialog box.
34
To look up an action in the Reference panel, do the following: 1. To open the Reference panel, click the Reference icon in that looks like a book with a question mark on it located in the right corner above the Script pane. The left pane of the Reference panel is a carbon copy of the left pane of the Actions panel. 2. Navigate to the action you want to know more about. As you click the title of each book, a description of the type of actions found in that book is displayed in the right pane. 3. Click an action to display information about it in the right pane of the Reference panel, as shown in Figure 2-9.
Opens ActionScript description window Reference panel icon
Figure 2-9: To find out more about any action, open the Reference panel.
35
Tip
To the right of the Reference icon is an inverted triangle. Click the triangle to open another window that displays a brief description of a selected action. This window also displays information about the action used to create a selected line of code in the Script pane.
36
Figure 2-11: You use the commands in this menu to change ActionScript modes and much more.
37
Figure 2-12: With the Action panel context menu, frequently used commands are just a mouse click away.
38
The formatting identifiers may seem a bit foreign until you see them used in context. Listing 2-1 shows some ActionScript code that uses all of the identifiers.
The code in Listing 2-1 was assigned to a button that, when clicked, loads an image and defines two variables. The curly brace in line 1 instructs Flash that this is the beginning of the actions that will execute upon release of the mouse button. In the second line of code, the two forward slashes designate a comment. It may help if you think of comments as memory joggers. You can use comments to remind yourself, or another designer working on the project, what the lines of code following the comment actually do. In this case, they load a JPEG image and define the names
39
of two variables. The parentheses in the second line group the image with the target the image will be loaded into. The semi-colons at the end of the lines 3 through 4 signify the end of a statement. Semi-colons are added automatically when you work in normal mode. If you forget to add one in expert mode, dont worry; the carriage return also lets Flash know youre ending a statement. The dot in _root.Target separates the path from the named instance of a movie clip. If the script was referencing a variable in the movie clip, an additional dot would appear before the variables name, for example _root.Target.xPos, where _root refers to the main timeline, Target is the instance name of a movie clip and xPos is the variable name. The dot in _root.Name is used to refer to a variable called Name on the root timeline. The solitary curly brace at the end of the code tells Flash to end the actions associated with the on (Release) event in the first line of code.
After entering a line of code into the Script pane, examine the color Flash assigns to each word. For example, if you enter gotoandplay, the syntax is in error and Flash highlights the words with black. When you change the code to gotoAndPlay, the highlight changes to blue, indicating Flash recognizes it as an action. Syntax coloring helps you construct correct code when working in expert mode, but you still have to be concerned with the parameters.
Tip
If you dont want syntax coloring, would like to change the colors currently used to highlight syntax, or would like to change any other part of the Actions panel, you can modify certain features and functions by choosing ActionsOptions Preferences or by choosing Preferences from the Actions panels Options menu. For more information on changing ActionScript preferences, refer to the manuals that shipped with the software.
40
Code hints
When you work in expert mode, Flash takes away the parameter text boxes, but fortunately provides you with a second line of defense: code hints. Code hints are enabled by default. When you enter code in the Script pane and Flash recognizes the code as the beginning of an Action, it posts a code hint. The code hint provides information you can use to properly format the line of code you are creating. The actual hint varies depending on the action you are using. For example, if you enter gotoAndPlay (, Flash displays the dialog box shown in Figure 2-13. In this case, you have two possible sets of parameters. The first parameter tells you the frame number (or label) you want the Flash Player to go to and play must be included between parentheses. The second parameter is accessed by clicking the arrow to the right of the number 2, which tells you that you can also supply the scene followed by the frame number separated by a comma, and the scene and frame must be surrounded by parentheses. Parameters are discussed in detail as they pertain to certain actions. For now its helpful to know that you can get help when you need it with code hints.
41
Exporting a script
As you gain expertise in ActionScript, you find yourself creating some fairly lengthy scripts. The Script pane, while a good text editor, is not exceptionally large, and it doesnt have a spell check. If you prefer the luxury of editing your scripts in a word processor, you can do so by exporting a script and then opening it in a word processor. You can also export scripts to share with other designers or store in a folder for use with another project. To export a script: 1. Select the object or keyframe the script is assigned to. 2. Open the Actions panel. 3. Open the Action panel Options menu as discussed previously, and choose Export as File to open the Save As dialog box. 4. In the Save As dialog box, navigate to the folder where you want to store the script and enter a name in the File Name field, click Save, and Flash saves the file with the AS (ActionScript) extension.
Importing a script
You can export any script saved in the AS format. Importing a script is useful when you want to use a previously saved script in a new movie, use another designers script, or used a saved script on another frame or object in the same document.
Note
When you import a script, all other code assigned to the keyframe or object is overwritten.
To import a script: 1. Select the keyframe or object you want to use the imported script with. 2. Click the Actions panel and then open the Actions panel Options menu. 3. Choose Import from File, and the Open dialog box appears. 4. Navigate to the folder where you store your scripts, select the desired script, and click Open.
42
Tip
If you inadvertently overwrite or delete a desired bit of code, you can restore it by choosing EditUndo, choosing Undo from the ActionScript context menu, or by pressing Ctrl+Z (Windows) or +C (Macintosh).
43
44
Movie clip symbol icon Graphic symbol icon Figure 2-14: Symbols you create are stored in the document library.
45
On the CD-ROM
Navigate to this chapters folder on the CD-ROM and copy the AS-02Start.fla file to your hard drive. Use your computers operating system to disable the read-only attributes of the file.
To begin creating your first ActionScript, launch Flash and then choose FileOpen, navigate to the AS_02Start.fla, and open it. Figure 2-15 shows the partially completed document.
Before you get down to brass tacks and begin adding code to the button, take a look at the elements you already have in place. First and foremost is the image youll be manipulating with ActionScript. The image is a JPEG file embedded in a movie clip. An instance of the movie clip has already been created on Stage and labeled myClip. Whenever you create a movie clip and want to manipulate it with ActionScript, you must give it a unique name.
CrossReference
I show you how to create movie clips and name them in Chapter 6.
Below the movie clip is text to instruct the user what to do and two input text boxes. The text boxes have been assigned variable names: opacity and scale. Variables are used to store and dispense information.
46
On the timeline are two keyframes. Notice the lower-case a in each frame. This designates that ActionScript has been applied to the frames. Listing 2-2 shows the code assigned to the first keyframe.
If youre fairly new to ActionScript, the last listing may seem a bit daunting. The first two lines of code define two new variables, the same variables used for the input text boxes. The initial value of the variables is nothing, or null in programmer speak. The last three lines of code are defining the initial state for the three properties that will be manipulated with ActionScript. The properties are set to make the movie clip fully visible at its original size. The second keyframe contains a single action stop (). This is to keep the movie clip from looping between the two keyframes. When the movie initially starts, the first keyframe is used to initialize the variables, and then the movie advances to frame 2 where it stops, awaiting input from the user. When the user clicks the button, the values entered in the text boxes are what change the opacity and size of the image. You may be wondering why it is necessary to set the initial state for each property. In spite of the instructions to enter a value between 1 and 100 to re-scale the image, the input text box will accept a value higher than 100. Every good designer knows that when you scale an image larger than its original size, pixels must be redrawn, resulting in image degradation. If the user enters a value larger than 100, the movie will jump back to the first keyframe, no changes will be applied to the image, and the values for the variables will be reset to null. This is the interactivity that will occur in the published movie after you program the button by following these steps: 1. Select the button and then open the Actions panel. Notice that the title of the panel changes to Actions Button. 2. Click ActionsConditions/Loops. The first line of code you create checks to see if the user enters a value greater than 100. 3. Add the if action to the script. Remember you can add the action by dragging and dropping it into the Script pane or by double-clicking it. After you add the action to the script, Flash
47
displays a warning, <not set yet>, in bright red. This is Flashs way of telling you it needs more information in this case, the condition the statement will be evaluating. 4. Place your cursor inside the Condition parameter text box and type the following: _root.scale>100. This is the condition you want Flash to check for. The name of the variable is
scale, but you need to add the path in order for Flash to find the variable. In
this case the variable resides on the root timeline, which is designated by
_root followed by a dot.
5. With the last line of code still selected, click the Movie Control book and then add the goto action to the script. Flash adds the action to the script, as shown in Figure 2-16. This is the action that occurs if the user enters a value greater than 100. Notice the number of parameter text boxes associated with this action.
CrossReference
6. Add the else action from the Conditions/Loops book to your script. The information you supply with this action is what will occur if the conditional statement evaluates as false; in other words, if the user enters a valid value of 100 or less.
48
Tip
When you open an Actions book, it stays open. If you work with a lot of actions in a single script, it can become cumbersome to scroll past all of the actions in the open books. Close a book after adding an action to your script, or better yet, if you know all the actions youll use in a script, open the Index book (an alphabetical listing of every action) and scroll directly the needed action.
7. Click ActionsVariables and then double-click set variable to add the action to the script. 8. Place your cursor inside the Variable parameter text box and then click the Insert a Target path icon the looks like a crosshair. After you click the icon, Flash opens the Insert Target Path dialog box shown in Figure 2-17.
Figure 2-17: In this dialog box, you find the path to every named instance of a movie clip.
9. Click the button that says myClip and then click OK to add the path to the script. After you click the button, the code _root.myClip appears in the Variable parameter text box followed by a flashing cursor that looks like an I-beam. This signifies that you can add text to the parameter box. 10. Type a dot (.) immediately following the word Clip and then click the Properties book. 11. Double-click the _alpha property to add it to the script. 12. In the Value Parameter text box, enter the word opacity and then click the Expression checkbox. Your finished line of code should read: _root.myClip._alpha = opacity;. Notice that Flash automatically added a semi-colon to designate the end of the statement. The code you just created sets the alpha property of the movie clip equal to the value the user enters in the Input Text box. 13. Now all you have to do is change the x and y dimensions of the movie clip to the value users will enter in the input text box with the variable name scale.
49
14. To change the y dimension, repeat Steps 7 through 12, substituting the _yscale property (found in the Properties book) for _alpha in Step 11, and the word scale for opacity in Step 12. To change the x dimension, follow Steps 7-12, using the _xscale property instead of _apha in Step 11 and the word scale in place of opacity in Step 12. 15. Scroll to the top of the top of the Actions panel and click the first line of code that reads: on (release) {. Flash created this line of code automatically when you added an action to the button. By default, Flash uses the release mouse event when you add an action to a button. Upon release of the button, the code following the statement is executed, which in this case is what you want. However, you can use more than one event handler with a button. For example, you can program the button so that it responds to the release of the mouse button, as well as a keyboard entry. 16. Click the Key Press checkbox, place your cursor in Key Press text field and then from your computer keyboard press Enter. Your finished code should be identical to Listing 2-3.
To test your handiwork, choose ControlTest Movie to make Flash publish the movie and open it in another window. Enter a value in both text boxes and then press the button to scale the image and change its opacity. Press the Reset button and the movie goes to frame 1 and the initial values are restored. Enter a value greater than 100 in the right text field and then press the Enter button, or press Enter. If you followed the above steps exactly, the image didnt change size and the text fields were reset to null values.
CrossReference
Flash MX represents a considerable upgrade from Flash 5. If youre not familiar with how to use the new Flash tools to design and publish a movie, refer to Flash MX Bible by Robert Reinhardt and Snow Dowd (published by Wiley Publishing, Inc.).
50
Designer Notes
In this chapter you learned how to use the Actions panel to create ActionScript. You learned how to use the Actions panel in normal and expert mode. Now you should have a good idea of how to format your code and check the syntax of your code. You also received a brief overview of symbols as they relate to ActionScript. At the end of the chapter, you used the Actions panel to create your first ActionScript. In future chapters, youll expand on this knowledge and use the building blocks from this chapter to create ActionScript elements for your designs. In the next chapter, you are introduced to some techniques for planning your ActionScript.
C H A P T E R
In This Chapter
The evolution of an ActionScript Fleshing out your idea Planning your Flash movie Getting it down on paper Creating new ideas Chapter project: Drawing outside the lines
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
52
Figure 3-1: Use ActionScript to evolve your idea into a finished creation.
When you create a Flash movie and use ActionScript, you provide choices for your viewer. The choices you provide determine the ebb and flow of your movie. And you use ActionScript to direct this ebb and flow. For example, you can use ActionScript to control what type of background music the viewer hears when viewing your design or provide the user with the option of viewing your site in silence. A Flash design with ActionScript can be compared to the organization of a traditional HTML design. When the user makes a choice by clicking a button, another page loads. With a bit of JavaScript, you can add some interactivity to the HTML page that is, if youre willing to learn the JavaScript necessary to accomplish the task. While a traditional HTML design even a JavaScript-enriched design limits the amount of interactivity you can add to a design, ActionScript leaves you with a multitude of options. In Chapter 1, you learned some of the effects you can achieve with ActionScript. In Chapter 2, you popped the hood of the Actions panel and got a little grease under your fingernails and experienced a bit of the power you have at
53
your disposal when you learn how to utilize ActionScript. But before you go any further and create your own designs from scratch, its important to understand how a typical ActionScript gets the job done. When you create a Flash movie, the Flash Player begins playing the first frame of the movie and plays each frame in succession; that is, it plays each frame in succession unless you use ActionScript to change the direction of your movie. For example, if youre creating a Flash design for a corporation and want to limit access to certain parts of the movie, use ActionScript to stop the movie while the user enters a password in an input text box, which is stored in a variable. You further direct the flow of the movie by using a conditional statement to evaluate the user name, and based on the result, determine whether a part of the movie will play or not. You can create a similar scenario to create a password-protected site. This is also a conditional statement that evaluates whether a password is valid, in which case the condition is true, or invalid, in which case the condition is false. When you create a statement that evaluates as either true or false, you create a Boolean expression. The flow of an ActionScript that evaluates a Boolean expression is illustrated in Figure 3-2.
if statement is false
if statement is true
if statement is true
ActionScript ends
54
Another way to control the flow of a movie is with a loop. Certain loops repeat a given set of actions for a number of iterations before branching out to the next line of script or branching out to another part of the movie after the loop is completed. This type of control is useful when you have to duplicate an object in your production x number of times. Another type of loop repeats a certain action while a set of conditions evaluate as true. For example, if you use Flash to create a game, you can create a script that supplies a new question while the number of incorrect answers is less than the value you want to allow the player. When the player exceeds the number of incorrect choices, the movie branches out in another direction. GAME OVER! Figure 3-3 shows the flow of an ActionScript that loops while a condition is true.
ActionScript code
False
End ActionScript
Loop
True
ActionScript code
Figure 3-3: You can create an ActionScript where certain actions repeat while a given set of conditions is true.
You can use even the most mundane ActionScript to control the flow in certain parts of your production by instructing the Flash Player to go to a certain frame, play the movie, or stop the movie. But no matter how you decide to control your movie with ActionScript, your best ideas may all add up to naught without a bit of prior thought and pre-planning.
55
Getting inspired
When a client entrusts you to take his or her corporate banner and display it on the Internet, getting your facts together is part of the planning process. Be sure that there is a good flow of communication between designer and client. Make sure you know all your clients expectations up front. That way neither your client nor yourself will be disappointed when you initially present your finished production for approval.
Tip
While youre gathering your facts, ask the client for his or her competitors URLs.
Armed with your clients expectations and his or her competitors URLs, you can begin doing some research. Visit the Web sites supplied by your client to get an idea of what your client is up against. Compare your clients ideas to what his competitors are doing and figure out what you need to do in order to build a better mousetrap. Without this information, youll never be able to give you client a leg up on his competitors. At this stage, its also import to ask yourself if your clients ideas are over the top or clash with the competitions. If this is the case, dont be afraid to diplomatically approach your client and seek the middle road between expectation and reality. Remember, your reputation as a designer will be at stake when you put the finished production out there for all the world to see. In addition to the competitor URLs supplied by your client, you should also make it a point to visit Web sites of other companies offering the same product or service as your client. You can find these sites by typing a few keywords into your favorite search engine. Many of these sites will supply additional inspiration and add fuel to the creative fire your client first kindled when approaching you. After you complete your research, you may begin to see a pattern for the type of industry youre creating the site for. Certain items may be staples for the industry you are creating the site for. Armed with this information, your clients expectation, and your own vision, you are now ready to begin planning the design.
56
Figure 3-4: You can create a storyboard in FreeHand and export it for use in Flash.
57
After you put the idea down on paper, you know what you need to get the job done. If youre not familiar with a needed action, you can learn how to use it by referencing a chapter in this book, the online Flash Reference panel, or figure out another way to achieve the same effect. If you create your plan line by line as you do ActionScript, you can transfer your idea directly from paper to the Actions panel. Listing 3-2 shows the ActionScript necessary to pull of the idea planned in Listing 3-1.
58
Another tool many designers like to use is a visual mind map. If youre not familiar with this concept, you start with a clean sheet of paper, and as the ideas pop into your head, you create a circle and jot the idea inside it. Create additional circles for each idea and draw a line to connect related ideas. For example, if you know the effect you want to achieve with ActionScript, jot the effect down in one circle and create additional circles for each action you need to pull off the effect. Creative planners who are visually oriented take this technique one step farther. They start with a clean sheet of paper and jot their ideas down on small sticky notes. With ActionScript, you can use a different colored sticky note for different elements of your script; for example, variables in pink, loops in yellow, and so on. The advantage of this technique is that as your ideas for a script change or evolve, you can reposition the sticky notes or add new ones. After youve done your mind mapping, you can create a written plan or launch Flash and begin fleshing out your idea.
While youre creating your storyboard and planning your ActionScript, make a shopping list. On your shopping list, include the assets youll need for the project: client artwork, clipart, code you need to learn, and so on. Collect everything on your shopping list before starting the project.
59
imports them, double-click the Eraser tool to clear the Stage. The imported images are all in the document Library for future use, and you can create an images folder to store all your bitmaps for the project in one place. You can use the same technique to import sounds and video files. As you gather the assets for your project, remember that you can always use such as buttons and movie clips from your other Flash productions. Choose FileOpen as Library and navigate to the *.FLA file that contains the assets you want to use. After choosing this command, Flash opens the other document Library. Drag the needed assets from one library and drop them into the current document Library. If youve been a fastidious designer and used graphic symbols as the basis for your buttons and clipart, you can modify the symbols to quickly update any instances of the symbol used in buttons or movie clips. Remember, if you create your ActionScript effects and store them in movie clips, you can use them in any production. For more information on creating modular ActionScript, refer to Chapter 6.
Tip
If you dont know how to create the needed ActionScript for a movie, you can often find out how to achieve the effect by visiting one of the many Flash tutorial Web sites. From many of these sites you can download a detailed tutorial, complete with a working example. Open the example in Flash and then open the Actions panel to see how the Flash author pieced together the ActionScript to pull off the effect.
60
Locate the drawOutside.fla file, which youll find in this chapters folder on the CD-ROM that accompanies this book. Copy the file to your hard drive and use your computers operating system to disable the files read-only attribute.
1. Launch Flash and open the drawOutside.fla file. The file, as shown in Figure 3-5, consists of two layers: Background and Mask. If youve created masks in Flash before, you may notice that the mask layer doesnt look like a Flash mask layer. Thats because the object doing the actual masking is the circle that looks like a compass. ActionScript has been used to convert this movie clip into a mask. 2. Choose ControlTest Movie. After Flash opens the file in another window, you notice the circle is rotating slowly and acts as a mask to an underlying image. You also notice that the background image is darker. Click the circle, and it increases in size so you can drag it to reveal other parts of the image. After youve finished experimenting with the movie, close the window to return to movie-editing mode. 3. Click the circle to select it and then open the Actions panel to view the code applied to the movie clip (see Figure 3-6). The code used to convert the movie clip to a mask may seem a bit foreign to you. You learn how to create a mask with ActionScript in Chapter 16. The third line of code modifies the movie clips rotation property. This is what sets the mask spinning. Lines 7 and 8 change the size of the mask after the movie clip is clicked. If you havent modified your Actions panel to view line numbers, doing so will help you follow the rest of this tutorial. Click the View Options button and select View Line Number from the menu.
61
Mask layer
Figure 3-5: ActionScript has been used to convert the movie clip to a mask.
Figure 3-6: This ActionScript code converted the movie clip to a mask.
62
4. Click the third line of code to select it and in the Expression field, change +1 to 1. This sets the rotation of the circle in a counterclockwise direction. If youre feeling frivolous, change the value to a larger number. The rotation wont be as smooth, but it will give you an idea of the way ActionScript animation works. 5. Select the seventh line of code and in the Expression field, change the value from 200 to 150. 6. Select the eighth line of code and in the Expression field, change the value from 200 to 50. 7. Select the Mask layer and then select the background image. 8. Open the Actions panel and you should see the following code:
onClipEvent (load) { _root.MC2._alpha=25; }
9. Select the second line of code and change the value from 25 to 50. 10. Choose ControlTest Movie. As a result of your changes, the background movie clip is now brighter and the mask is rotating counterclockwise. When you click the mask, it becomes an ellipse. After youre done experimenting with the movie, examine the ActionScript used to code the mask. This will give you a taste of what youll learn in upcoming chapters.
Designer Notes
In this chapter, you learned how an ActionScript flows and how a single idea evolves into a finished production. You also learned some techniques to chart your ActionScript course. I showed you time-saving techniques, and you learned a few ways to plan your work. In the next chapter, youll learn how to use some basic actions to navigate within a movie.
Happy accidents
When youre between projects and have some time on your hands, launch Flash, create a new movie, and then create or import some objects. Embed the objects in movie clips and have some fun. Begin experimenting with different properties to create an effect. Try the exact opposite of something thats worked for you before. Replace one action with a different one or add additional actions to a script. There are no rules here just try something, anything. If your script falls flat on its face, so what? No pixels were damaged and you dont have a client breathing down your neck. But if your script does work and you create something truly spectacular, or even moderately spectacular, jot down some notes (or add comments to your script) to remind yourself how you achieved the effect and save the file.
II
In This Part
Chapter 4 Charting the Timeline of Your Movie Chapter 5 Creating Basic Interactivity Chapter 6 Creating Elements for Your Movie Chapter 7 Taking Control of Your Movie Chapter 8 Creating Variables to Store and Dispense Information
C H A P T E R
In This Chapter
Controlling the timeline Adding actions to keyframes Adding actions to objects Working with buttons Navigating with ActionScript
f you dont use ActionScript in your Flash documents, your published movies play in linear form, starting with frame 1. Each frame plays in succession until the movie ends. As you know, without ActionScript, when the movie reaches the last frame, it loops back to the first and continues playing over and over. This is fine if youre creating a Flash banner for use in an HTML document. However, if you want to give your standalone Flash designs the kind of interactivity that keeps viewers glued to their monitors, you need to take control of the timeline. When you take control of the timeline, you choreograph the production, deciding what frame will play next when a keyframe is reached and what movie clip or scene will play when a button is clicked. When you use ActionScript to control the flow of a movie, you give your viewers a choice of what to view. In this chapter, you learn how to use ActionScript to advance a movie to a specific frame or scene. You also learn how to assign actions to a button. In addition, you find out how to open up a Web page when a keyframe is reached or a button is clicked, a handy feature when you need to link to HTML content or launch an HTML page after a Flash intro has played.
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
66
Creating a frame
You create a frame when you need to copy content without making a change. This is used primarily for graphic objects. However, when you create a keyframe on one layers timeline and need to display the content from another layer timeline without making a change, you also need to add a frame to carry the content forward.
67
Keyframe with objects and ActionScript Timeline window Keyframe with objects Blank keyframe Keyframe with motion tweening
Stage
Figure 4-1: You use keyframes to create major event changes in a movie.
To create a frame: 1. Click the frame where you want the content to advance to. 2. Choose InsertFrame. Alternately, you can press F5. When you use this command, Flash adds a frame with a hollow rectangle to designate the end of the frame range and copies the graphic content from the previous keyframe to the frame you select when you invoke the command. You can also add frames to a range of frames. This is often necessary to slow down a sequence of action. To add frames, click one or more frames, choose Insert Frame, and Flash inserts the number of frames you select when you invoke the command.
68
To speed up the action, you may need to delete one or more frames. To do so, select a frame or several frames, choose InsertRemove Frames (or press Shift + F5), and Flash removes the number of frames you select when you invoke the command.
Creating a keyframe
You create a keyframe whenever you make a major change in your movie. The change can be replacing one object on Stage with another, manually changing a property of an object by moving it, changing the property of an object with ActionScript, or using ActionScript to alter the movie in another way. To create a keyframe: 1. Click the frame where you want the change to occur. 2. Choose InsertKeyframe. Alternately, you can press F6. When you create a keyframe not adjacent to the previous keyframe, Flash fills in the blanks with standard frames.
If you need to remove the content or ActionScript from a keyframe but still need the frame for timing purposes, choose InsertClear Keyframe. If you need to convert several standard frames to keyframes, select the frames and then choose ModifyFramesConvert to Keyframes. To convert a selection of frames to blank keyframes, choose ModifyFramesConvert to Blank Keyframes.
Labeling a keyframe
When you create ActionScript, it is often necessary to reference a particular frame in your code. Your ActionScript can refer to the frame by its number. However, when you fine-tune a movie by adding or deleting frames, the action that once occurred on frame 26 now occurs on a different frame, which causes a major
69
problem with your script as its still referring to frame 26. The solution is to label your keyframes. When you label a keyframe, the label appears on certain parameter text box drop-down menus. When you refer to a frame label in a script, the Flash Player always searches for the label, no matter how many frames youve added or subtracted from your design. 1. To label a keyframe: 2. Select the keyframe you want to label. 3. Open the Property inspector. 4. In the <frame label> field, enter a name for the frame and press Enter or Return. When you enter a name for the keyframe, choose a label that reflects what happens. This makes it easier for you to decipher the reason you created the keyframe after working several hours on other parts of your production. It also makes it easier for other designers on your team to figure out exactly what youre doing. When you label a frame, a red flag appears in the frame on the timeline, followed by the frames label. If you have several contiguous keyframes, or the frame label is long, it will be truncated. Hold your mouse over the labeled keyframe and a tooltip with the frames name appears, as shown in Figure 4-2.
Labeled keyframes Figure 4-2: You can use a labeled keyframe to help foolproof your ActionScript.
70
2. Choose InsertLayer, or click the Insert Layer button that looks like a file folder preceded by a plus sign (+). 3. After Flash creates the layer, click the default layer name, type Actions, and then press Enter or Return. After you create the Actions layer, remember to use this layer for any keyframes you create that will have ActionScript.
71
keyframe that tells the Flash Player to stop playing the movie or direct the movie to another keyframe. You can also allocate multiple actions to a keyframe that define variables, evaluate expressions, or check to see whether a set of conditions exists. To create ActionScript for a keyframe: 1. Select the keyframe you want to create ActionScript for. 2. Open the Actions panel. When you select a keyframe and open the Actions panel, the panels title bar reads, Actions Frame. If the title bar reads differently, you havent selected the keyframe try again. 3. Navigate to the action by either opening the book it is stored in, or open the Index book and select the appropriate action. Remember the Index book lists every Flash action in alphabetical order. 4. After selecting an action, use your favorite method to add it to a script. Remember you can double-click an action to add it to a script, or drag and drop it directly into the Script pane. You can also click the plus sign (+) above the Script pane and choose the desired action from a drop-down menu. 5. Continue adding actions as needed to complete your script. Figure 4-4 shows a script with several actions assigned to a keyframe. Notice the parameter text boxes above the Script pane. These boxes differ depending on the action and will be discussed as needed.
Figure 4-4: You use the Actions panel to write a script for a keyframe.
Caution
It is possible to select a standard frame and create an ActionScript. However, the code you create will be assigned to the previous keyframe on the timeline. Always make sure you have a keyframe selected when attempting to create a script on the timeline.
72
Creating Buttons
You also use buttons to add interactivity to your Flash productions. When you add buttons to a movie, you give the viewer a choice: to click or not to click. You can program a button to direct the viewer to another part of the movie when clicked, load additional content when clicked, and much more. Buttons can play a large part in any Flash movie you publish. If youve worked with Flash for any length of time, youve probably already created a button or two. However, many designers dont take advantage of ActionScript and use Flash for simple animations that are incorporated with their HTML designs. If you fall into this category, this section will give you a brief overview on how to create a button. If youre an experienced pro at creating buttons, feel free to skip to the next section.
73
Figure 4-5: You can use as many layers as needed to create a button.
Tip
You can use any graphic for a button. However, if your design calls for a JPEG image for a button face, it may increase the file size of the published movie. If the image is being used exclusively for the button, you can use the Trace Bitmap command with fairly high settings to convert the image into Flash vector objects.
74
Down: The content in this keyframe is activated when the users mouse clicks the button. This is the most logical state to add a sound. If you add a sound to the down state, remember that it will continue playing until conclusion. Use a sound less than a second in length, such as a single musical note or a mechanical noise like a camera shutter button being clicked. Hit: The graphic you use in this keyframe defines the target area of the button and is not visible. If you have a small button icon in the Up state, create a shape for this frame that is slightly bigger than the icon, thus giving the viewer a bigger target area.
75
button to trigger a myriad of events. As previously mentioned, you can use a button for interactive elements in your movie and navigation. You can also use a button to modify objects on Stage. For example, you can program a button to change the size or opacity of an object. You can also assign multiple actions to a button.
Figure 4-6: You use invisible buttons to add interactivity to movie clips.
To program a button: 1. Select the button you want to program. 2. Open the Actions panel. When you open the Actions panel after selecting a button, the title reads: Actions Button. If you see anything else, reselect the button. 3. In the left pane of the Actions panel, navigate to the desired action and add the action to your script by double-clicking it or dragging and dropping it into the Script pane. If you work in normal mode, Flash automatically adds on(Release) to your code. This is the event that triggers the action you selected. Release, the default mouse event, executes the action when users release their mouse after clicking the button. (You learn how to use all the mouse events in Chapter 5.) Figure 4-7 shows a button with the goto action assigned to it.
76
77
78
Figure 4-8: You supply the parameters that direct the movie to the desired frame.
You find the getURL action in the Browser/Network Control book and also in the Index book. To direct your movie to another Web page: 1. Select the button or keyframe you want to assign the action to. 2. Open the Actions panel. 3. Add the getURL action to your script. After you add the action to your script, the parameter text boxes shown in Figure 4-9 appear above the Script pane. 4. In the URL field, enter the URL of the page you want to open when the action executes. Enter the full path for the URL, for example: http://www. dasdesigns.net/index.htm. Alternately, you can check the Expression checkbox and enter an expression that, when evaluated, directs the movie to the desired Web site. 5. Click the button to the right of the Window field and choose one of the following: Self: Opens the URL in the same window as the link. Blank: Opens the specified URL in a new browser window. Choose this option, and your Flash movie plays in the background. Parent: Loads the URL in the window of the frame that called the link. If the frame isnt nested, the URL opens in the full browser window. Top: Loads the URL in the full browser window, removing all frames. 6. In the Variables field, accept the default Do Not Send or click the button to the right of the field and choose Send Using Get or Send Using Post. You use the Send Using Get option to send variables to another Web page; Send Using Post to send the variables to a CGI script at the URLs server. Figure 4-9 shows the getURL action as assigned to a button.
79
Figure 4-9: You use the getURL action to direct the movie to a specified URL.
80
The JavaScript in line 4 of the above code specifies whether scrollbars should be included and specifies the width and height of the new window. Change these values as needed to suit the page you are opening. Specify dimensions smaller than the average Internet surfers desktop size of 800 x 600. If your Flash movie references more than one new window, copy lines 2 through 4 of the above code and change the first line to newwin2, entering the URL for the second URL on the second line.
Designer Notes
In this chapter, you learned how to take control of your movies timeline with ActionScript. You learned how to apply ActionScript to keyframes and buttons as well as how to use basic actions to direct the flow of your designs. In the next chapter, youll take your knowledge one step further and learn how to create movie clips. Mouse events and clip events are also covered.
C H A P T E R
In This Chapter
n the last chapter, you learned how to assign actions to buttons and keyframes. Buttons can be used for many things. One of the most obvious is navigating to another part of your design: When the button is clicked, the movie advances to a predetermined frame. Buttons can also be used to trigger a change, for example, moving an object on Stage. You can also use buttons to load additional content or open up another Web page.
Creating movie clips Assigning actions to an object Embedding video files Understanding clip events Understanding mouse events Using buttons for navigation Using buttons for interactivity
Actions can also be assigned to objects in your Flash movies. However, you cant just assign an action to a graphic symbol. If you want to modify a graphic object, it must reside in a movie clip. And in order for Flash to locate that movie clip, it must have a name. In this chapter, you learn how to create movie clips and label them. You also learn how to assign multiple actions to a button that does different things depending on how the users mouse interacts with the button. When the mouse interacts with the button, it is an event. The code you assign to an event determines what happens when the event occurs. Movie clips also have events. As you progress through this chapter, you learn how to use these ActionScript event handlers.
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
82
clip can consist of a single frame containing a single bitmap or graphic symbol you need to modify, or it can contain several frames of animation or even a video clip. When you create a named instance of a movie clip symbol, you can address it with ActionScript. To create a movie clip: 1. Choose Insert New Symbol to open the Create New Symbol dialog box shown in Figure 5-1. 2. Enter a name for the symbol, choose the Movie Clip behavior, and click OK to enter symbol-editing mode. 3. Create the keyframes and desired animation using either frame by frame methods or tweening. 4. If the movie clip is to be a container for ActionScript, select the first frame, open the Actions panel, and create the desired script. 5. Click the Back button to exit symbol-editing mode.
Figure 5-1: You define a symbols behavior with this dialog box.
83
and create a blank keyframe by pressing F7. Then you can begin adding your content. On the root timeline, create a separate layer for each movie clip. If you have several movie clips in your movie, consider creating a layer folder. Figure 5-2 shows a document with several movie clips housed in a layer folder.
Layers outside folder Figure 5-2: You can create individual movie clips for your designs content.
When you create a movie clip that will play on demand, you need the clip to cycle back to the first frame when its finished playing. You do this by adding the goto action to the last frame of the clip. Figure 5-3 shows the timeline of one of the movie clips from Figure 5-2 with ActionScript on the last frame that returns the clip to the first frame.
Figure 5-3: After a movie clip plays, this ActionScript returns it to the first frame.
84
File Type Audio Visual Interleaved Digital Video Motion Picture Experts Group QuickTime Movie
If you have DirectX 7.0 or greater installed on your machine (Windows only), you can import the following video file formats:
File Type Audio Video Interleaved Motion Picture Experts Group Windows Media Video
If you work on the Windows platform and have both QuickTime and DirectX 7.0 or better installed, you can import all of the formats listed above.
Tip
If you are importing a video to play in a movie clip, follow the preceding steps to create a movie clip symbol with a stop action on the first frame. If the finished movie clip will be on Stage at all times, create a blank keyframe on frame 2 and select it prior to importing the video.
To import a video file into Flash: 1. Choose FileImport. 2. Navigate to the file you want to import and click Open. The Import Video dialog box appears. Choose one of the following options: Embed video in document embeds the video file. Choose this option and you can publish the file as a *.SWF movie.
85
Link to external file creates a link from the document to the external video file. If you choose this option, you can only export the document as a QuickTime *.MOV movie. This option is available only if you are importing a QuickTime *.MOV movie. 3. If you choose to embed the video, the Import Video Settings dialog box appears (see Figure 5-4). 4. Drag the Quality slider to set the level of compression for the imported video. Alternately, you can enter a value between 0 and 100. Choose a high setting, and little compression is applied to the video, resulting in a higher quality clip at the expense of a larger file size. Lower settings result in higher compression, which yields a smaller file size with a tradeoff in image quality. 5. Drag the Keyframe slider to determine how often a keyframe is created. A keyframe is a frame with complete data. The frames before and after the keyframe only contain data that is changed from the keyframe. Enter a lower value and the embedded video will have more keyframes, resulting in a faster seek time at the expense of a larger file size. 6. Drag the Scale slider to reduce the image size of the embedded video. Alternately, enter a value between 1 and 100. A setting of 50 percent effectively halves the image size. If your published movie will be viewed by users with slower processors, reducing the image size improves playback performance. 7. Enable the Synchronize to Flash document frame rate option and the playback of the embedded video will be synchronized to the document frame rate. 8. Click the button to the right of the Number of Frames to Encode per Number of Flash Frames field and choose an option from the drop-down menu. The default rate of 1 to 1 plays one video frame for each Flash frame. Choose a different setting to create a smaller file size at the expense of choppy motion. For example, if you choose a rate of 2 to 1, the embedded video plays 1 frame for every 2 Flash frames; in other words, 1 frame out of 2 is dropped resulting in uneven motion. 9. If audio is present in the video you are importing, the Import Audio option is enabled by default. Deselect this option to import the video without sound. 10. Click OK to import the video. If the file is large, Flash displays the Importing dialog box, which gives you a visual representation of the operations progress. 11. After the file finishes importing, Flash displays a dialog box telling you how many frames must be created to play the video from beginning to end. Click Yes, and Flash creates the necessary frames.
86
Figure 5-4: You control the quality and size of the embedded video by modifying import settings.
After importing the video, you can add the necessary ActionScript to finalize your movie clip. For example, you may want to create a new layer and a blank keyframe at the last frame of the video and use the goto action to return to the first frame of the movie clip, which if youve created it as outlined in the previous section, will be a blank frame with a stop action. If you dont add some type of control to the embedded video, it will loop continuously.
Tip
If you have a large number of videos in your design, embedding them all in a single movie results in a large file size and a lengthy download. Create separate documents for each video file and publish them as .SWF movies. Use the loadMovie action to load each file on demand. (You learn to use the loadMovie action in Chapter 7.)
87
3. In the <Instance Name> field, enter a name for the symbol. When you name an instance, you create a target for your ActionScript. Remember to choose a name that describes what the symbol does. This is especially import if you have a document with several named instances in it. Every named instance appears as a button in the Target Path dialog box. Without having a descriptive name to go by, you can easily select the wrong target.
Figure 5-5: You name an instance to provide a target for your ActionScript.
88
event before the selected action. You can modify the clip event by clicking the line of code that lists the clip event. Doing so opens the text parameter boxes shown in Figure 5-7.
Figure 5-6: You can use ActionScript to modify the properties of an object. Clip events
Figure 5-7: The clip event you choose determines when the ActionScript executes.
When you create ActionScript for an object, you can choose any of the following clip events: Load: The actions that follow this clip event execute when the movie clip loads.
89
EnterFrame: The actions that follow this clip event execute when entering a frame of the movie clip. If the movie clip is a single frame, the actions that follow are constantly evaluated and executed. Unload: The actions that follow this clip event are handled after the first frame of the movie clip plays. Mouse down: The code that follows the Mouse down event occur after the down stroke of the users mouse button. Mouse up: The actions that follow this clip event are handled after the user releases the mouse; the upstroke of the mouse button. Mouse move: The code that follows this clip event occurs whenever the users mouse is moved. Key down: The actions following this clip event occur when a key is pressed. You use the getCode method of the Key object to tell Flash which key must be pressed. Key up: The action associated with this clip event occurs when a key is released. You use the getCode method of the Key object to tell Flash which key must be pressed. Data: The script associated with this clip event occurs when data is loaded as a result of the loadMovie action or loadVariable action. If you prefer, you can specify the clip event before creating your code. To do this, you add the onClipEvent action to your script before adding other actions. To assign the event handler to a movie clip object: 1. Select the movie clip instance to which you want to apply the code. 2. Open the Actions panel. 3. Click ActionsMovie Clip Control and then double-click the onClipEvent action. After you select the action, Flash opens the parameter text boxes previously seen in Figure 5-7. 4. Accept the default Load event or select another event. 5. Select the action you want to occur after the clip event.
90
entering the target path every time you use a different action. You can alleviate some of this repetitive action using the with action. When you use the with action, you specify the target path to the movie clip once. The actions that follow occur with the specified target. The with action is quite handy when you have a number of actions that occur when a button is clicked. To add the with action to a script: 1. Select the object you want to which you want to assign the action. 2. Open the Actions panel. 3. Click ActionsVariables and then double-click the with action. After you select the action, Flash displays it in the Script pane followed by <not set yet>, which is highlighted in red (see Figure 5-8).
Figure 5-8: You use the with action to associate the code that follows with a specific object.
4. Place your cursor inside the object field and then click the Insert a Target Path icon that looks like a cross-hair to open the Insert Target Path dialog box shown in Figure 5-9. 5. Click the button that matches the symbol you want to target. Flash adds the target path to the script. 6. Add the actions that you want to occur with the targeted clip. Listing 5-1 shows code that changes the opacity, x scale, and y scale properties of a movie clip named myGirl when the user release the mouse button.
91
Figure 5-9: Every named instance of a symbol appears in this dialog box.
92
4. To change the mouse event, click the line of code that contains the event handler and choose one of the events in the parameter text box area. Note that you can use more than one event to trigger an action. Make sure that the only events selected are the ones you want to trigger the actions that follow. Each mouse event is covered in detail in the next section.
93
The movie clip associated with the ActionScript in Listing 5-2 has a stop action on frame 1. When a user rolls over the button, frame 2 plays and the movie clip begins playing. As soon as the user rolls past the buttons target area, the action associated with the rollOut event begins and the movie clip goes to frame 1 and stops.
Tip
Notice that the code for the rollOver and rollOut events are similar. When you create lines of code that you know will be similar, you can save yourself a lot of time using the Actions panels context menus Copy and Paste commands. Select the lines of code that are similar and then right-click (Windows) or Ctrl+click (Macintosh) and choose Copy. Click the last line of code in the Script pane, open the context menu, and choose Paste. You can now select an individual line of the code you just pasted and change parameters such as the mouse event that will be used or frame that will play when the code is executed.
94
95
Interactive interface elements are discussed in greater detail in Chapter 12. In Chapter 4 you learned to use some basic actions to navigate to different parts of a movie.
You can quickly create navigation for a design by using the actions in the Movie Control book in conjunction with a button symbol. Figure 5-11 shows a navigation menu created for a photographers Web site.
Figure 5-11: You can use buttons to create navigation for your designs.
If you study Figure 5-11, you notice the buttons are all the same size yet have a different look. Instead of creating a new symbol for each button, create one button, open the Document Library, and duplicate the button. You can then edit the duplicated button symbol to change the graphics and text displayed. Repeat this for the other buttons, and you can quickly create a navigation menu.
96
object displayed in an e-commerce design. As you gain more familiarity with ActionScript, youll think of new and exciting ways to add interactivity to your designs with buttons.
On the CD-ROM
Navigate to this chapters folder and copy the file button.fla to your hard drive. Use your operating system to disable the files read-only attributes. Open the file in Flash and choose ControlTest Movie. Click the various buttons to get an idea of what you can create for your own designs. After you finish exploring the interactive buttons, return to movie-editing mode to select a button and open the Actions panel to find out what makes the button tick.
Designer Notes
In this chapter you learned how to create the basic elements for interactive Flash designs. You learned how to create movie clips and how to choose a clip event to trigger an action. You also learned to program buttons for use as navigation devices and as triggers for interactivity in your designs. Finally, I showed you how to trigger an action upon a key press. In the next chapter, youll learn to work with symbols, create loops, and more.
C H A P T E R
In This Chapter
Working with symbols Creating loops Generating random numbers Creating functions Creating modular ActionScript Chapter project: Navigating to a random frame
98
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
99
3. Choose InsertNew Symbol. The Create New Symbol dialog box opens. 4. Enter a name for the symbol, choose the Movie Clip behavior, and click OK. Flash enters symbol-editing mode. 5. Select the first frame and then choose EditPaste Frames. Flash pastes the frames and layers you copied from the main timeline. If the movie clip is displayed on Stage at all times, you dont want it to play until called by the click of a button. To prevent the movie clip from playing when it loads, follow Steps 6 through 8; otherwise, go to Step 9. 6. Select every frame in every layer by clicking the first frame on the first layer and then dragging across and up. 7. With all the frames selected, click the first frame and drag it one frame to the right to create a blank keyframe in the first frame. 8. Add the stop action to the first frame of the top layer. If the movie clip will have actions on several keyframes, its advisable to insert a layer for your actions. 9. Click the Back button or click the current scene button to exit symbol-editing mode. The new movie clip is added to the document Library for future use.
Nesting symbols
When you need to include other graphics or movie clips within a shell movie clip that contains your ActionScript, you create a new symbol and drag an instance of
100
the symbol from the document Library into the newly created symbol. For example, when you create drag-and-drop elements for your Flash designs, you nest an invisible button in the movie clip and then assign the startDrag action to the invisible button. Remember you can also import objects such as bitmap images when youre modifying a symbol. Nesting a bitmap within another symbol keeps everything compact and tidy. And if for any reason you need to change the bitmap currently nested in the movie clip, you can use the Swap Bitmap command, which will be discussed before the end of this chapter. To nest one or more symbols within another movie clip: 1. Create a new movie clip as discussed previously. 2. Choose WindowLibrary. 3. Select the Library item you want to nest in the symbol and position it on Stage. 4. If the nested symbol is a movie clip and youre going to use ActionScript to modify it, open the Property inspector and enter a name in the <Instance Name> field. 5. At this point you can drag other symbols from the document Library and nest them within the newly created movie clip. After you add the other graphics needed for the symbol, click the Back button to exit symbol-editing mode. Alternately, you can double-click anywhere on Stage. Figure 6-2 shows an example of symbol nesting.
Figure 6-2: When you nest symbols, you can create a movie with a smaller file size.
101
Swapping symbols
A Flash document is often a work in progress, especially when youre creating a design for a client. Clients have been known to change their minds more frequently than politicians change their opinions. If your design is peppered with symbols that are nested in other symbols, you can quickly change the look of a symbol by swapping one symbol with another. If you design for clients who frequently change artwork while the design is still in production, this feature is invaluable. To swap one symbol with another: 1. Select the symbol you want to swap. If the symbol is nested within another symbol, double-click the parent symbol to enter symbol-editing mode and select the nested symbol. 2. Open the Property inspector and then click the Swap button. Alternately, you can choose ModifySwap Symbol. The Swap Symbol dialog box opens, as shown in Figure 6-3. Every symbol in the document Library is listed in this dialog box. 3. Click a symbol to view it in the preview window. 4. Click OK to swap the symbol. Alternately you can double-click the symbols name.
Figure 6-3: You can quickly swap one symbol for another to change your document.
Swapping bitmaps
Designers are fond of using bitmaps in their work. Bitmaps liven up your design, but you must use them judiciously to avoid bloating the file size of the published movie. If you create a document with bitmaps and decide a bitmap in your production isnt quite right, you can easily swap it for another bitmap in the document Library. The ability to swap bitmaps is new to Flash MX.
102
To swap one bitmap for another: 1. Select the bitmap you want to swap. If the bitmap is nested in another symbol, double-click the parent symbol to enter symbol-editing mode and then select the bitmap. 2. Open the Property inspector and click the Swap button. Alternately, you can choose ModifySwap Bitmap. The Swap Bitmap dialog box (shown in Figure 6-4) opens displaying a thumbnail of the currently selected bitmap and a list of other bitmaps in the document Library. 3. Click a bitmap to view it in the preview window. 4. Click OK to swap the bitmap.
If you work for a client who frequently changes bitmap content in a Flash design, when it comes time to update the movie, open the *.FLA file you created the document with. Import the new bitmaps and then swap them.
Creating Loops
You can create two kinds of loops in Flash: frame-based loops and ActionScript loops. You create a frame-based loop when you want a certain number of frames to continue playing. A frame-based loop is the basic ingredient in a preloader; the same frames loop until the movie content is loaded. You use actions to create the frame loop and then use ActionScript to launch the main movie when enough content has loaded for the production to play without interruption. When you have ActionScript code that is repeated several times, you can simplify things by creating a loop. When you create a loop, you save the hassle of having to write the same bit of code several times. For example, if you use the duplicateMovieClip action to populate the movie with shimmering stars,
103
you have to create a new name for each new clip the action creates. Instead of manually entering the code and naming the clips MC1, MC2, MC3, and so on, you create a loop for the number of clips you want to create.
Looping frames
To create a frame loop, you use the goto action on the last frame of a movie clip. If the movie clip is always on Stage, use the stop action on the clips first frame, which is blank, and have the movie loop back to the second frame. A frame-based loop is what keeps repeating the animation in a preloader.
Figure 6-5: If you create a loop that cant execute in a single frame, Flash displays this warning.
You have three types of ActionScript loops: Do While: This ActionScript loop repeats while a given set of conditions is true. When the condition is false, the loop terminates. For: This type of loop executes a specified number of times before termination. When the loop finishes, the next action in the script occurs. While: This loop is similar to the do while loop, but the condition takes precedence over the action being performed while the condition is true. When you create a while loop, the loop terminates as soon as the condition is false. With a do while loop, the action following the condition executes once more after the condition is false.
104
In the example above, the properties of six instances of a movie clip called mc0 through mc5 are being changed. Lines 4 through 6 change the properties of each clip. Without the loop, youd have to codes each property change for each clip, resulting in a whopping 18 lines of code. When you use a for loop, you eliminate many lines of code and free your time for more products tasks. The second line of code initializes the loop. The parameters for the action appear between the parentheses. The first parameter sets the initial value of i equal to 0, which is identical to the first element in an array. If youre not familiar with using an array to store data, youll be up to speed after reading Chapter 9. The second parameter of the for action is the condition that must be true for the loop to continue. The loop in the above example continues as long as i is less than or equal to 5. The third parameter in the code determines the increment for each loop. In this case, the increment is 1. The third parameter could have been written as i+1, but ++i is a code shortcut that does the same thing. The lines of code between the curly braces execute as long as the condition is true. In the above example, each movie clips opacity is reduced by 25 percent and scaled to 80 percent of its original size.
Note
There is also a post increment operator that would be written as i++. The post increment operator is used when two variables are present. The post increment operator increases the value of the first variable, but not the variable the operator is attached to. If you use a post increment operator in a loop with a single variable, the loop will fail because the value of the variable will never increase.
105
You can use the for action on a keyframe, a movie clip, or a button. To add a for loop to your script: 1. Select the object or keyframe where you want the loop to occur. 2. Open the Actions panel and then click ActionsConditions/Loops. Then double-click for. The action is added to your script, and three parameter text boxes appear above the Script pane. 3. In the Init field, enter the beginning value for the loop. You assign the beginning value to a variable. You can create any variable name, but its easier to use a single letter. Standard programming practice favors the letters i, j, or k for loop variables. Note that you do not have to begin a loop with 0 or 1. In the example in Listing 6-1, you enter an initial value of 3 to change the properties of the last three clips. Note that you can also create a loop that counts down (decrements) by starting with a high value and decreasing the value during each iteration of the loop. To begin the loop with a variable named i with a value of 1, enter i=1. 4. In the Condition field, enter the condition that must remain true for the loop to continue. The condition is the number of iterations before the loop ends. If you set the variables value less than or equal to a given value, the loop ends when that value has been reached. For example, i<=10 stops the loop when the value of i is equal to 10. 5. In the Next field, enter the value the loop will increment by. You can use any applicable value in this field. For example, if you create a loop to change the property of every other movie clip, youd enter a value of i+2, assuming your initial variable is i. To increase the initial loop value by a value of 1, you can use the code shortcut ++i, to decrease the value of the loop by 1 enter i. 6. Enter the code that you want to occur during the loop. Figure 6-6 shows the Actions panel with the for action selected. The code in this figure uses the trace action to record the loop as it counts down from 10 to 1. The trace action is used when you need to trace the value of a variable when debugging a document. In Figure 6-6, it is used for demonstration purposes. To gain a bit of experience with the for action, launch Flash, duplicate the code in Figure 6-6, and choose ControlTest Movie. Flash publishes the movie in another window and the Output Window displays the variable as the for loop counts down to 1. After you successfully run the script, close the window. Open the Actions panel and modify the script, entering different values and conditions to count up or count down by different increments.
106
You find the while loop in the Loops/Conditions book. When you add it to a script, you have only one parameter: Condition. Enter the condition that must occur for the loop to continue and then enter the actions you want to execute while the condition is true.
107
You also find the do while action in the Loop/Conditions book. When you add the action to your script, you have only one parameter to specify, the condition. After you specify the condition, select the first line of code and then add the action(s) you want to execute before the condition is evaluated.
108
In the above listing, the value of the variable i is set to a random number between 1 and 50. The next line of code is a while loop that creates duplicates of the movie clip as long as the value of k is less than the value of i, which is a random number. The fifth line of code increase the value of the variable by k by 1 with each loop.
CrossReference
You can also generate random motion, change an objects size to a random value, and more. To achieve this, all you have to do is set a property of an object equal to a random value. Listing 6-5 shows ActionScript that changes a movie clips position, size, and alpha settings.
Each line of code in the above example is an expression that sets the object property equal to a random number. The steps that follow show you how to create a variable with a value equal to a random number. If youve used variables before, you know they are placeholders for data. If youre not familiar with variables, consider this your baptism by fire.
CrossReference
To create a variable with a value equal to a random number using the Math object, do the following: 1. Select the keyframe or object you where you want to declare the variable. 2. Open the Actions panel and then click ActionsVariables. 3. Double-click the set variable action to add it to your script. Two text parameters boxes appear above the script pane. 4. In the Variable field, enter a name. You can choose any name for a variable except a reserved keyword. (Naming variables are covered in detail in Chapter 8.) For the purpose of this demonstration, enter myRandomNum.
109
5. Place your cursor inside the Value field. 6. In the left pane of the Actions panel, click ObjectsCoreMathMethods. 7. Double-click the random method to add it to your script. In the Value field, the following code appears: Math.random(). This code is sufficient to generate a random number between 0 and 1. To generate a random number within a specific range, go to Step 8. 8. In the Value field, click to the right of the last parentheses and type * followed by the highest number you want to generate. 9. Click the Expression checkbox to the right of the Value field. When you generate create a variable equal to a number, it is a mathematical expression. If you fail to check the Expression checkbox, Flash reads this as text data. The code in Listing 6-6 creates a variable with a random value between 0 and 50.
Rounding numbers
When you use the random method, Flash generates a random value between 0 and 1. When you multiply this value by a whole number, Flash does not round the number up or down. If youre creating a random value to reference a frame or need a randomly generated whole number for your script, you need to add additional code to round the number up or down. To do this, you use the round method of the Math object. The example below shows you how to create a variable that has a value equal to a variable number that has been rounded off. To round a random value: 1. Follow Steps 1-4 of the previous section to create a variable called myRandomNum. 2. Place your cursor inside the Value field. 3. In the left pane of the Actions panel, click ObjectsCoreMathMethods. 4. Double-click the round method to add it to your script. In the Value field the following code is added: Math.round(). You enter the value you want Flash to round between the parentheses. 5. Place your cursor between the parentheses and in the left pane of the Actions panel, double-click random. The code in the Value field should now read: Math.round(Math.random()).
110
6. Place your cursor before the last parenthesis, type an asterisk (*) followed by the highest number you want to randomly generate. 7. Click the Expression checkbox to the right of the Value field. Listing 6-7 shows the code needed to generate a random value between 0 and 150 that is rounded in accordance with mathematical principles.
Creating a function
When you use several lines of code repeatedly in a design, assigning the same code to different movie clips can become tedious. You can save a considerable amount of time if you create a function for the repetitive code and then call the function when you need it. You can specify the parameters of a function, the type of object the function can be used with, or create a function with no parameters that you can use with movie clips, and other programmable objects. If you use a function repeatedly in a movie, its a good idea to create it on the movies first frame. To create a function, do the following: 1. Select the object or keyframe where you want to create the function. 2. Open the Actions panel. Then in the left pane of the Actions panel, click ActionsUser Defined Functions and then double-click function. Flash adds the action to your script and opens two parameter text boxes, as shown in Figure 6-7.
111
3. In the Name field, enter a name for the function. When you choose a name, choose one that reflects what the function does. This makes it easier for you to remember what the function does as well as other designers working on the project. Dont include any spaces in the function name. If you must designate the difference between two words in a function name, use an underscore or capitalize the first letter of the second word, similar to the way the Flash programmers designate between words in an action. Remember you can use a reserved keyword as part of a function name, but you cannot use just a keyword. 4. In the Parameters field, enter the parameters for the function. For example, if you are using the function exclusively with movie clips, mc is the proper parameter. If youre not sure which objects youre going to use the function with, leave this field blank. 5. After you enter the parameters, enter the actions you want the function to perform. Listing 6-8 shows a function that sends the movie to a random frame in a movie clip on the root timeline.
112
Calling a function
When you need to use a function, you call it. You can call a function from a keyframe in the movie or call it from a movie clip or button. When you call the function, you associate it with a named instance of a movie clip in your production. To call a function, do the following: 1. Select the keyframe or button you want to call the function from. 2. Open the Actions panel. Click ActionsUser Defined Functions and double-click call function. The action is added to your script and three parameter text boxes appear as shown in Figure 6-8. 3. In the Object field, enter the path to the function. If the function is declared in a keyframe before the function is called, you can leave this parameter blank. If the function is in a keyframe on another timeline, click the black Insert a Target Path button. In the Insert Target Path dialog box that appears, click the button that represents the movie clip the function is stored in. 4. In the Method field, enter the name of the function. 5. In the Parameters field, enter any parameters associated with the function. For example, if the function parameters address a movie clip, enter the name of the movie clip with quotation marks. Listing 6-9 shows the code used to call the function rndFrame that is embedded in a movie clip called My Function. The function is being used to send the movie to a random frame in a movie clip called diva.
113
114
Open this chapters folder on the CD-ROM and copy the buttonPhotography.fla file to your hard drive. Use your operating system to disable the files read-only attributes.
115
Figure 6-9: You can use a function to go to a random frame when a button is clicked.
8. Place your cursor inside the Value field, and in the left pane of the Actions panel, click ObjectsCoreMathMethods book and then double-click round. The action is added to your script and your cursor is flashing between parentheses. A frame label is a whole number. Without the round method of the Math object, Flash would never be able to equate the value generated by the random method of the Math object with a frame and the script would fail. 9. From the Methods book, double-click random. The random method of the math object is added to your script. This is where you add the number that represents the upper limit of numbers you want randomly generated with the function. In this case, youre dealing with two movie clips with a different number of frames. In order to generate a number that represents the last frame of each movie, you use a movie clip property called total frames that returns the total number of frames in an instance of a movie clip.
116
10. Place your cursor between the parentheses after the word random and type _root[mc].. You enter mc between the square brackets to reference the parameter you declared in the function, mc for movie clip. 11. Open the Properties book and then double-click _totalframes. Click the Expression checkbox. Your second line of code should now read:
rndLabel=Math.round(Math.random()*(_root[mc]._totalframes))
12. Click ActionsMiscellaneous Actions and then double-click evaluate. You have one parameter box to work with: Expression. The expression you create will display a randomly generated frame when the function is applied to a movie clip. 13. In the Expression field, type the following code: _root[mc].gotoAndPlay(rndLabel). This line of code instructs the Flash player to play the frame number generated in the last line of code. This looks quite a bit different than the lines of code you normally associate with the goto action. In this case, youre addressing a movie clip on the root timeline, which is why you end up manually entering the expression rather than selecting the goto action from the Actions panel.
117
The object field is left blank because the function resides on the root timeline. If you make the function modular by creating it in a movie clip, you would enter the movie clips path in the object field. 5. Select the button on the right side of the Stage and repeat Steps 2 through 4, with the exception of typing ss2 in the Parameters field this time around. Test the movie and when you click the left button, the function directs your attention to a random frame in the first movie clip. Continue clicking the button and the function displays another frame. Click the right button and you see different frames generated in the second movie clip. When you tested the movie in the preceding project, you may notice that clicking the button did not change the image. There are two reasons for this: The random number generated may have been 0 and there is not a frame 0 on the timeline, or the same number was generated twice in succession. You can add conditional statements to your script that cause a different number to be generated if the number is a duplicate or 0.
CrossReference
Designer Notes
In this chapter, you started delving into your ActionScript tool kit. You learned to use symbols as ActionScript elements in your design and how to generate random numbers. You were introduced to a powerful ActionScript tool, the loop, which takes the drudgery out of writing repetitive code. Creating a user-defined function was also covered in detail. In the next chapter, you learn how to manage the content of your movies and keep the file size of your movies impressively small.
C H A P T E R
In This Chapter
esigners have a grand vision of their creations, often before they begin creating them. Even though Flashs strong suit is giving designers the capability to create fast loading, impressively small Web files (hence the acronym SWF), it is possible to break the bandwidth barrier by using every bit of eye candy known to Flash designers. If youve ever visited a Flash Web site that takes a long time to download, you have experienced the everything-but-thekitchen-sink Flash designer at work. That doesnt mean that you cant include everything but the kitchen sink in your Flash movie; you just need to take control of the process so you dont break the bandwidth barrier and lose visitors because of lengthy downloads. In this chapter, you learn a couple techniques to effectively manage the size of your grand design. First and foremost, you learn to break a Flash movie into logical segments. After all, you may be the greatest designer in the world, but people who view your Flash creation may not want to see all of it in one sitting or be patient enough to wait for it all to download. Then youll learn to load a movie into a target window.
Breaking a movie into segments Using the loadMovie and unloadMovie actions Loading a movie into a target Communicating between timelines Demystifying targets and paths Chapter project: Creating an organizational chart
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
120
example, if you are creating a site for a photographer, you can break the movie into four sections: the photographers biography, the photographers portfolio, services offered by the photographer, and the photographers contact information. Each of these sections becomes an individual movie that is loaded when the visitor clicks a button on the navigation menu.
Figure 7-1: The base movie for the Web site contains the navigation menu and banner.
When you plan the site, keep the overall size of each movie in mind. If youve created a compelling introduction, visitors will wait several seconds for a section to load, but not much longer than that. If youre forced either by a client or by design considerations to create section content that will take considerable time to load, consider creating an animated preloader as discussed in Chapter 14.
121
Understanding levels
When you load a movie you assign it a level, which determines how the content of the new movie is displayed. The base movie is always level0 in other words, the bottom floor. If you load another movie into level0, the base movie is erased with the new content. If, however, you load a movie into a higher level, the content is displayed on top of the base movie. If youre familiar with photo editing programs such as PhotoShop, levels in Flash work the same way layers in Photoshop do. For that matter, they work like the layers in Flash MX as content on a higher level eclipses anything on the level below it.
122
To create a template for section movies, follow these steps: 1. Open the base movie and choose FileSave As. 2. Name the file template. 3. Create a new layer and name the layer template. Remember that you can create a layer by choosing InsertLayer or by clicking the Insert Layer icon in the Timeline window. 4. Right-click (Windows) or Ctrl+click (Macintosh) and choose Guide from the drop-down menu. Any object you create on a guide layer will not be visible when the movie is published. You can also display objects on the guide layer (or any layer, for that matter) as outlines by clicking the rectangular icon to the left of the layers timeline. 5. Select the template layer and, using the Rectangle tool, create a rectangle that encompasses the blank area of the Stage. This rectangle serves as a visible guide to the area you use to create content for each movie you load into the base movie. Leave yourself a margin for error. Remember you can use rulers and the Property inspector to precisely size and place the template rectangle. 6. Delete all of the elements from the base movie. 7. Choose FileSave and youll have a template that resembles Figure 7-2.
Figure 7-2: Create a template to accurately place objects on Stage in section movies.
123
Notice the difference between this figure and Figure 7-1. The objects you create in the white rectangle will fill the blank area in Figure 7-1 when movies you create from the template are loaded into a higher level. After youve created the template, you can use it to create content for each sections movie. After you create a section movie using the template, choose FileSave As and christen the movie to reflect the section content; for example, about.swf. This is the name youll use in conjunction with the loadMovie action discussed in the next section.
Loading a movie
You can use the loadMovie action in one of two ways. You can assign the action to a button, which when clicked loads the desired movie, or you can assign the action to a keyframe, whereupon the movie is loaded when the keyframe is reached. To use the loadMovie action, follow these steps: 1. Select the button or keyframe that will trigger the loadMovie action. 2. Open the Actions panel and click ActionsBrowser/Network Control and then double-click loadMovie to add it to the script. If you assign the action to a button, choose the mouse event that will trigger the action. (For more information on mouse events refer to Chapter 5.) 3. In the URL field, enter the path to the movie youre loading. If the movie is in the same Web site, you can enter the relative path to the movie, for example, about.swf. If the movie is part of another Web site, enter the absolute path to the movie, for example, http://www.dasdesigns.net/about.swf. 4. In the field to the right of Level, enter the level you want to load the movie into. A Flash movie can have up to 99 levels. 5. If the movie you are loading contains variables and you want to load the variables into the base movie, click the triangle to the right of the Variable field and from the drop-down menu choose either Send Using Post or Send Using Get. 6. Close the Actions panel.
124
After you publish the movie, the specified movie will load when the keyframe is reached or the mouse event assigned with the button occurs. Figure 7-3 shows a typical ActionScript for the loadMovie action.
Figure 7-3: Use the loadMovie action to load additional content into your base movie.
Unloading a movie
As discussed previously, when you load a movie into a level, the loaded movie replaces the previous content of the level. If, however, you have movies loaded on different levels and load a movie into a level not previously used, the movies on the other levels continue to play and be visible. If this is not the effect you are after, you need to unload the movie(s) you no longer want to play. The unloadMovie action has one parameter: Location. To unload a movie, follow these steps: 1. Click the button or keyframe that will cause the movie to unload. 2. Open the Actions panel and click ActionsBrowser/Network Control and then double-click unloadMovie. If you assign the action to a button, specify the mouse event that must occur to initiate the action. 3. Click the triangle to the right of the Location field and from the pop-up menu, choose either Target or Level. 4. If you choose Target, click the Insert a Target Path button and click the target you want to unload the movie from. If you choose Level, enter the level the movie you want to unload was loaded into. 5. Close the Actions panel.
125
If you have more than one movie to unload, repeat Steps 2 and 3. By using the loadMovie and unloadMovie actions, you can take control of your movies and create an interactive experience for viewers of your Flash movies. You can also load movies of different dimensions by loading a published Flash movie into a target movie clip.
126
6. Open the Property inspector. 7. In the W and H fields, enter the width and height of the movies youll be loading into the target clip. 8. In the X and Y fields, enter a value of exactly half the x dimension and half the y dimension. This aligns the upper-left corner of the target movie clip for proper loading. Your movie clip should resemble Figure 7-4. 9. If the target movie clip will reside on a Stage with the same background color, open the Stroke panel, click the color swatch, and then click anywhere on Stage to match the rectangles stroke to the background color. After changing the rectangles stroke color, proceed to Step 13. If your background is a bitmap image, proceed to Step 10. 10. On the timeline, click the first frame to select it and drag it to frame 2. 11. Select the first frame and choose WindowActions to open the Actions panel. Then click ActionsMovie Control and then double-click the stop action to add it to your script. Assigning the stop action to the first keyframe prevents the rectangle on frame 2 of the target movie clip from being visible when the movie loads. 12. Select the second keyframe and assign the stop action to it. 13. Click the current scene button to exit symbol-editing mode. 14. Select the target movie clip from the document Library and drag an instance of it on Stage. 15. Position the target movie clip where you want the content to appear when a user summons it by clicking a button or when a keyframe on the timeline is reached. If you create a movie clip with a blank first frame, the only clue youll have to position the target is the movie clips registration point, a small filled circle sign. Remember that this is the upper-left corner of the target movie clip. If you created a storyboard and know the precise coordinates of the target clip, you can use the Info panel to position it. 16. Open the Property inspector and in the <Instance Name> field, enter a name, and then press Enter or Return.
Tip
When you create a complex movie with many elements, its good practice to first create a storyboard, as described in Chapter 3. The storyboard serves as your blueprint to precisely placing items such as target movie clips. Many designers have the ability to think visually. However, what looked great in your minds eye may not work when you try to do it in Flash. A few minutes with pencil, paper, ruler, and calculator can save you hours of frustration when youre under deadline to get a project ready for a client.
127
Figure 7-4: This target movie clip is properly aligned for loading a Flash movie.
128
4. In the URL field, enter the name of the movie to be loaded. Remember to include the .swf extension. 5. Click the triangle to the right of the Location field and choose Target from the drop-down menu. 6. In the field to the right of Location, select the default entry of 0 and then click the Insert a Target Path button to open the Insert Target Path dialog box and choose the Absolute Mode. Within the dialog box youll find an icon for every named movie clip instance in your movie, as shown in Figure 7-5. 7. Click the icon that corresponds to your target movie clip. 8. Click OK to close the Insert Target Path dialog box and within the Location field Flash replaces the default value of 0 with the correct target path, as shown in Figure 7-6. This figure shows the action applied to a button. Your ActionScript will differ if you apply the action to a keyframe. 9. Close the Actions panel. After you publish the movie, when the event that triggers the loadMovie action occurs, Flash loads the movie into the specified target movie clip.
Tip
Whenever you complete a milestone such as programming a button, its a good idea to test your handiwork. You can test the movie at its current stage of completion by choosing ControlTest Movie, or you can test a scenes current stage of development by choosing ControlTest Scene. If everything works as planned, save the file. Its always a good idea to periodically save a file in case a computer glitch causes Flash to become unresponsive.
Figure 7-5: You specify the target movie clip by selecting it in the Insert Target Path dialog box.
129
Figure 7-6: After you choose the target movie clip, Flash adds the path to your ActionScript.
130
Use the with action with target movie clips when the first frame of the clip is blank. Add the with action to the script and instruct Flash to go to and stop at frame 2. You then use the loadMovie action to load a specific movie into the target.
CrossReference
Figure 7-7: Click this button to open the Insert Target Path dialog box.
131
After you click the button, the Insert Target Path dialog box appears. Within this dialog box, youll find an icon for every named movie clip instance in your production. Click the desired icon, and the name of the target path appears in the Target Path dialog box. You can now add an object to the target path, for example, the name of a variable you need to address within the target timeline. After you close the Insert Target Path dialog box, Flash adds the name of the target path to the ActionScript. If you look at the Insert Target Path dialog box shown in Figure 7-8, you see that its not quite as simple as point and click. You have a decision to make in order to give Flash the information it needs to properly access the desired timeline. In the lower-right corner of the dialog box are two modes to choose from: Absolute, which uses the root timeline as the path starting point, and Relative, which uses the current timeline as the path starting point.
Figure 7-8: The mode determines the beginning point of the path.
132
Tip
If you prefer to venture boldly into the world of the programmer, you can save yourself some time by referencing a target path alias rather than using the Insert Target Path dialog box. You have three aliases to work with: _root, _this, and _parent. Use the _root alias to address the root timeline. Use the _this alias when you want to address the timeline of the movie clip calling the action. Use the _parent alias to address the parent movie clip from which the movie clip calling the action is nested.
133
List: Use this option to create a list. This option is similar to an array, but the list cannot be changed after an instance if the user-defined component is in your movie. The user can choose only one item from the list. String: Use this option to create a string literal object. Add this object to your component when you need the ability to frequently update text within a dynamic text box. Number: Choose this option when you need to create numeric data. You can use ActionScript to perform mathematical calculations on this type of data whereas if you enter numbers into a string object, Flash reads them as text objects. Boolean: Use this object type to define whether a particular object the user-defined component refers to is enabled (true) or disabled (false). Font type: Use this object type to refer to the font in a text object. Color: Choose this data type to define a text objects color. You can also use this object type if your component contains ActionScript that modifies and objects color with the setRGB method of the Color object.
Figure 7-9: Use this dialog box to define a user-defined components parameters.
8. In the Value field, double-click the default value to define it. If you define a variable (the default option), enter the value. If you choose Array, List, or Object, the dialog box shown in Figure 7-10 appears. Click the plus sign (+) to add a value; click the minus sign () to delete a value. To rearrange the order of a value, click the value and then click the Up arrow to move the value higher in the list; click the Down arrow to move the value lower in the list.
134
Figure 7-10: You can define the values of an array, list, or object with this dialog box.
9. Repeat Steps 3 through 7 for any other values you need to define in the user-defined component. You can mix different items within the rows of a user-defined component. For example, you can include variables and an array within the same user-defined component. 10. In the Description field, enter any notes that define what the user-defined component does. Think of the Description field as a memory jogger for when you modify the user-defined component as you update your clients site. The information you put in this field is also beneficial for other designers working on the same project. 11. Choose the Lock In Instance option to prevent modification of the Type parameters after an instance of the user-defined component is added to a movie. 12. Click OK to assign the objects to the component and close the dialog box. Figure 7-11 shows a user-defined component for a catalog item at an e-commerce Web site. Whenever a product description or catalog number changes, the designer updates the parameters of the user-defined component without having to revise any ActionScript. After you create a user-defined component, you create instances of the symbol on Stage. You can then modify the value of each parameter to suit the movie you are working on. After you create a user-defined component, you can use it in any other movie. Use the Open As Library command to open the document Library the user-defined component is stored in, drag it into the current document Library, and modify the parameters to suit your current production. Create user-defined
135
components for items you commonly use in your movies such as arrays and lists. When you create a user-defined component, you eliminate the drudgery of creating ActionScript and free your time up for adding more design elements to your production.
Tip
Macromedia has an extensive library of user-defined components available as extensions. You can download the free Macromedia Extension Manager, as well as user-defined components and extensions, from this Web site: www.macromedia. com/exchange/flash.
Figure 7-11: Update the parameters of a user-defined component instead of writing new ActionScript.
136
On the CD-ROM
To follow along with this exercise, copy the Orgchart folder from this chapters folder on the CD-ROM that accompanies this book to your hard drive. Use your operating system to disable the read-only attributes of each asset in the folder.
Figure 7-12: The base movie consists of an organization chart and a target movie clip.
Take a few minutes to examine the design of the movie before beginning the next section. Notice there is a blank placeholder at the top of the movie. An animated Flash banner named banner.swf loads into the placeholder when the movie begins. The ActionScript that loads the movie resides in the first frame of the movie on the Actions layer. This ActionScript also loads the image logo.jpg into the target movie clip on the right side of the Stage.
137
Notice the guide layer in Figure 7-12. This is set up so you know where the target movie clip resides. When you load a movie or image into a target movie clip that is the same color as the background, all you see is the movie clips registration point. On the guide layer, a circle has been created to highlight the movie clips registration point, and the movie clips instance name is displayed beside it. For the purpose of this project, the movie clip instance is called target. The guide layer will not be visible when the movie is published, yet it serves as a handy reference to each movie clip instances location and name. Create a guide layer whenever you have more than one target movie clip to identify in a movie. To view the movie at this stage of creation, choose ControlTest Movie. After Flash publishes the movie, you see the animated banner and corporate logo, as shown in Figure 7-13. Click any button other than CEO (the button youll be programming in a few minutes) and watch as the logo is replaced by the officers picture and name. After you finish examining the movie, close the file.
Figure 7-13: Each button is programmed to load a published movie into the target movie clip.
138
To program the CEO button: 1. Choose FileOpen, navigate to the orgChart.fla file, and click Open. 2. Using the Arrow tool, select the CEO button. 3. Open the Actions panel. 4. Click ActionsBrowser/Network and then double-click loadMovie to add the action to your script. Accept the default (on)Release mouse event. 5. In the URL field, type ceo.jpg.
Note
The ability to load a JPEG image into a movie is a new and exciting feature of Flash MX. Previously, you needed to create a separate movie and import a JPEG when you wanted the ability to load a JPEG image from an external source.
6. Click the triangle to the right of the Location field and choose Target from the drop-down menu. 7. Select the 0 in the window to the right of the Location field and then click the Insert a Target Path button to open the Insert Target Path dialog box. 8. Click the button named target and then click OK to close the dialog box. 9. Click ActionsVariables and then double-click set variable. Two parameter text boxes appear above the Script pane. 10. In the Variable field, type Name and in the Value field, type John Walker. Name is the variable assigned to the dynamic text box used to display the officers name. When the button is clicked, text changes to reflect the new value of the variable. If for any reason you dont like the name John Walker, feel free to change it. However, Name needs to remain the same. 11. Repeat Step 10 to create a new variable named Title with a value of Chief Executive Officer. Your finished ActionScript should be identical to Figure 7-14. 12. Close the Actions panel and then choose ControlTest Movie. When you click the CEO button, the ceo.jpg file loads into the target movie clip. 13. Choose FilePublish, and Flash republishes the file to reflect the added ActionScript. Congratulations. Your movie is complete.
Tip
If you create a design or technique youre especially proud of and dont want the rest of the world to know how you did it, create a base movie with no graphic elements and one keyframe. Assign the loadMovie action to the keyframe and use it to load the interface or intro movie. You can then use the loadMovie action to load additional content when a button is clicked. Although you can choose Protect From Import when you publish the movie to prevent other designers from opening the movie in Flash, savvy designers will still be able to find a published movie from their browser cache. When you create a movie in this fashion, other Flash designers wont be able to pull your design from their browsers cache because the base movie is blank.
139
Figure 7-14: The button is programmed to load the movie when clicked.
The techniques you used to finish the organizational chart movie can be used with any movie. For example, you can create an effective movie for a clients product catalog by creating a main movie with an interface and banner and then creating a movie for each product category the company represents. You then use the loadMovie action to load each product category movie into the main movie on demand. Within each section, create a text button for each product and a target clip. Create an individual movie for each product that loads into the target movie clip. When the clients catalog needs to be updated, you simply modify the appropriate movies rather than redesigning the whole site. You can streamline the process even further by creating a user-defined component with an array of product names. When the client decides to refresh the product offerings, you update the array in the user-defined component.
Designer Notes
In this chapter, you added more ammunition to your ActionScript arsenal. You learned to manage a movie by breaking it into logical sections and then learned to program buttons to load content upon demand. Additionally, you learned to load movies and JPEG images of different sizes into a target movie clip. You experienced the power and flexibility you can add to your designs by creating user defined components. In the next chapter, you learn to use variables to store and dispense information.
C H A P T E R
In This Chapter
Understanding the different variable types Creating variables Understanding data types Creating arrays Evaluating conditions with statements Using logical operators Chapter project: Generating random quotes
142
file cabinet filled with neatly organized folders of data you can retrieve in an instant. You also learn how to create conditional statements. A conditional statement evaluates an outcome. In plain English, a conditional statement does something if a given set of conditionals evaluate as true.
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
143
When the variable full name is displayed, the result is as you would expect, Jane Doe. Notice the space between the quotation marks between firstName, and lastName. You know this is a string literal value because it is surrounded by quotation marks. Without this space, the variables would run together and youd end up with JaneDoe. One more thing you need to notice about the third line in the above example is that the value of the variable fullName, which combines two string literal values, is not surrounded by quotation marks. Thats because the variable must be evaluated by Flash as an expression. An expression is when you combine: The values of two variables Different kinds of variables Hard numeric values and variables to perform a mathematical computation. In the above example, the expression is combining two string literal values to produce a third. If the variable fullName is not designated as an expression, the third line of code in the example above reads as follows: fullName = firstName +\ \ + lastName; and when the movie is published or tested variable fullName is displayed as: firstName + + lastName. Whenever you create a variable to combine the values of two or more variables with string literal data, you must specify it as an expression.
144
While on the subject of combining variables, its important to understand how Flash combines numeric literal values. Consider Listing 8-2. In this example, you see two variables that are numeric literal data. The third line of code uses an expression to combine them. Everyone knows that 4 + 6 = 10, but the variables in the first two lines of code are not specified as expressions. The quotes around each value identify the value to the Flash Player as a numeric literal value, and Flash combines the literal data to produce a result of 46 when the script is executed. In order to add the two values as a numbers, you specify each value as an expression. When you specify a value as an expression, the Flash Player no longer recognizes the value as numeric literal data. Listing 8-3 shows the subtle difference (the lack of quotation marks around the variables values) in the code when a variables value is designated as an expression. The value of the variable designated in the third line of code will now be 10.
About expressions
When you create a variable and designate its contents as an expression, you create a variable that can be evaluated using mathematical functions. In Listing 8-3, each variable is designated as an expression. The third variable uses a mathematical expression to produce a result that youd expect when adding two numbers. You can also create an expression that performs multiple operations. An example of this is the expression you created to generate a random frame in Chapter 6s project. In addition to using numeric data to perform mathematical operations, you can also use a variable whose value is designated as an expression to evaluate the properties of an object. For example, if you need to use the x position of movie clip named myClip, you create a variable and set it equal to the x position of the movie clip. After you declare the value of the variable as an expression, you end up with a variable that looks something like this: xPos=_root.myClip._x where xPos is the name of the variable and _root.myClip._X is the value. Because the value of xPos is declared as an expression, you can now use it as part of a mathematical expression.
145
The ++ operand and operand are shortcuts. Whenever you need to increase or decrease a value by 1, you can use these shortcut keys. However, notice there are two ways to format these operands; you can put them before or after the variable you are incrementing or decrementing. Where you place the operand is all important when creating a script, especially when using these operands in a loop. Listing 8-4 and Listing 8-5 show the different values returned by placing the operand before or after a value being increased or decreased by 1.
146
The code in Listing 8-4 returns a value of 125. You would use this syntax if your script called to increase the value of variable a by a value of 1 while leaving the value of variable b unaffected. The code in Listing 8-5 returns a value of 124 for b, but returns a value of 125 for a.
Caution
If you create a for loop and use the post-increment syntax to increase the value of the variable, the script will fail because the value of the variable would never increase. This in effect creates an endless loop, which causes the Flash Player to crash.
When you create expressions for your ActionScript, you can create an expression that uses multiple operations. For example, you can multiply a variable by a randomly generated number and then divide that computation by another value. Just remember to separate each operation with parentheses and remember which operators take precedence over the others so the expression generates the expected result.
147
Creating a Variable
You create a variable whenever you need to store data in your movie or retrieve data input from a movie viewer. Youve already created a few variables in projects presented earlier in this book. When you branch out and begin creating variables for your own designs, there are a few things you need to remember. Like everything else in ActionScript, variables have a set of rules you must adhere to otherwise, your script will fail or youll get unexpected results.
Naming a variable
When you name a variable, its in your best interests to choose a name that describes what the variable does, yet at the same time remember the acronym KISS: Keep It Short, Simple. This is especially important when you use the same variable repeatedly in a design. One typo and Flash wont pass the value of the variable and your script will fail. Mistyped variables are one of the main reasons an ActionScript fails. Fortunately, you have tools to track the value of variables when debugging your ActionScript.
CrossReference
There are other things to consider when naming a variable. You cannot include any of the following when naming a variable: Reserved words and commands: If you use a reserved keyword or command to name a variable, Flash may mistake it as an action. Therefore, you cannot use break, case, continue, date, default, delete, else, function, if, in, instanceof, new, on, return, sound, switch, this, typeof, var, void, while, or with as a variable name. You can use reserved words as part of a variable name; for example, the name dateToday doesnt cause the script to run improperly. Punctuation: You cannot use any of the following punctuation as part of a variable name: {}, ; , or (). Also, if you begin a variable name with two forward slashes (//), Flash mistakes the variable as a comment. Flash objects: You cannot use any of the Flash objects as variable names as they will render the object inoperable. Date, Sound, Key, Math, and so on are all names of Flash objects.
Note
When you choose a Flash object as a variable name and test the movie, Flash displays a warning in the Output window telling you the variable conflicts with a Flash object and will obscure it. When you see this warning, its best to choose another variable name.
Mathematical operators: If you use +,-, *, or / as part of a variable name, Flash mistakes the variable for an expression.
148
Spaces: You cannot include a spaces between words when naming a variable. For example, site password causes the script to fail. If you need to separate two names in a variable, use an underscore, as in site_password, or capitalize the second word, as in sitePassword. Numbers: You cannot precede a variable name with a number. A variable name of 4tier wont work; tier4 will. When you create a name for a variable, it should be displayed in black in the Script pane. If you violate a syntax rule when creating a variable, the offending variable is highlighted in red with the message The variable name you have entered
contains a syntax error.
Another thing to remember about variable names is case sensitivity. When you write ActionScript mode in expert mode, you must use the proper case. If you create a line of script gotoandplay (2) instead of gotoAndPlay (2), your script will fail. However, if you create a variable and initially name it myVariable and refer to it later as Myvariable, the Flash Player reads them as the same variable. When you need to retrieve the value of a variable on a different timeline, you must include the path to the variable in the variable name. If you create a variable called currentTime in a movie clip called digitalClock and add the movie clip to the main timeline of the movie, the path to the variable is _root.digitalClock.currentTime. Another thing to remember about variable names is that you can assign the same variable to a different timeline and Flash thinks it a different variable. For example, if you create another movie clip with the variable currentTime, Flash recognizes them as two separate variables, even though you may not.
Declaring a variable
When you decide to add a variable to your design, you must first create it, or as programmers are fond of saying, declare the variable. If you use a variable several times throughout the course of a movie, declare the variable on the movies first keyframe. If you use variables in a movie clip, declare them on the movie clips first keyframe. To create a variable, do the following: 1. Select the keyframe or object where you want to declare the variable. 2. Click ActionsVariables and then double-click setVariable. The action is added to the script and two parameter text boxes appear above the Script pane.
149
3. In the Variable field, enter a name for the variable. Remember to adhere to the variable naming conventions presented earlier in this chapter. 4. In the Value field, enter the value youre assigning to the variable. Click the Expression checkbox if the value will be evaluated. Figure 8-1 shows a typical script to create a new variable.
Figure 8-1: To use a variable in your design, you must first declare it.
150
Figure 8-2: You can declare several local variables for a movie clip with a single line of code.
Figure 8-3: You can pass values from one variable to another.
151
You can also set the value of a new variable equal to two variables that contain string literal data. You can use this to personalize a users experience. Users enter their names in an input text box, and you create a new variable to display a users name combined with a greeting message, as shown in Figure 8-4. Again notice that the Expression checkbox is checked. If youre combining string literal data with a variable as in this example, add a space after the string literal data (the word Welcome in this example) and the variables contents are correctly spaced when displayed in a dynamic text box. If you combine two variables with string literal data and need to place punctuation or a space between the two values, add the punctuation or space between the two variable names. Be sure to enclose the punctuation between quotation marks so it displays properly in a dynamic text box.
CrossReference
Figure 8-4: You can combine the contents of variables with string literal data.
152
In the above example, six client names have been neatly grouped in one array. In this example, you still have to enter each clients name into the array but you save the bother of creating numerous variables. What would you rather do create 50 variables or create one array with 50 elements? The clients array in the previous listing has six elements. The first element in an arrays position (also known as offset), is always 0. When you need to refer to an element in the array, you refer to it by its offset. Therefore, if you wanted to create a variable named customer that retrieves information about your third client, the variable would look like this: customer=clients[2]. Notice that the array element is surrounded with square brackets. You can use the elements from two arrays and combine them in a single variable. For example, you can store the names of each client contact person in a different array called contacts. When you create the array, you use the same array offset for the client contact person as you did in the clients array. The array offset for the client and contact person are the same. If you need to create a variable that displays the name of the client and the contact person, it would look something like this: custContact = The CEO for +clients[2]+ is + contacts[2] +.. When you cross reference different arrays, this is known as cross indexing. In the example above, each element for the clients array corresponds with the same element in the contacts array. In the custContact variable example, notice the addition of the string literal data. You can combine string literal data and array data to display just about anything in your designs. At the end of the chapter, youll be using array data to generate random quotes.
Creating an array
When you create an array, you create an instance of the Array object. You set the instance of the Array object equal to a variable. The Array object has various methods you can use to manipulate the contents of an array and join the contents
153
of one array to another. The Array object also one property that you can use to measure the number of elements in an array. Youll be using this property in the project at the end of this chapter. When you decide to add an array to your design, you create a variable and set its value equal to the Array object. After you create the array, you add elements to it. When you go to the trouble of creating an array, chances are you use it often in the design. Therefore, its good practice to define the array on the first keyframe of the movie or the first keyframe of the movie clip the array is housed in. To create an array: 1. Select the keyframe where you want to create the array. 2. Click ActionsVariables and then double-click setVariable. 3. In the Variable field, enter the name of the variable you want associated with the array. 4. Place your cursor inside the Value field. 5. In the left pane of the Actions panel, click ObjectsCoreArray and then double-click newArray. The code newArray() is added to your script. 6. Click the Expression checkbox. Thats all you need to do to create an array. The next step is to add the individual elements to the array.
154
Tip
If you create arrays with multiple elements, create the data in your favorite word processing program. Enter the name for each element, remembering to separate the elements with a comma and include quotation marks for string literal data. If your word processor has smart quotes, turn them off as they will cause your script to fail if you copy them into the Actions panel. Select the array data and then copy it to the clipboard. In Flash, place your cursor between the parentheses and then choose Paste from the context menu. Working in a word processor is easier than creating copious amounts of data in the Script pane. As an added bonus, your word processor probably has a spell checker.
155
2. Enter the number of elements in the array. Remember that the first element of an array is 0. If youre creating an array with 20 elements, enter 19. Listing 8-7 shows the code for an associative array with 20 elements.
You finish your code for an associative array by creating a variable with the name of the array element you want to store the data in and set the variables value equal to the data of the variable associated with the element. You do this by using the eval action, which evaluates the contents of the variable. Listing 8-8 shows the code needed to transfer data from the variable to its associated element in the array when the user clicks a button.
156
Notice that the code in Listing 8-9 begins with the if action. As long as the value of reelPos is less than the value of rightStop, the statement is false. As soon as the value of reelPos (the position of the moving slide show) is greater than the value of rightStop, the condition evaluates as true and the next line of code executes and sets the value of reelPos equal to rightStop (the boundary of the movie clip), which stops the clip from advancing further.
157
To create a conditional statement with multiple outcomes: 1. Select the keyframe or object where you want to create the conditional statement. 2. Add the if action to your script as outlined previously and add the actions that occur when the condition evaluates as true. 3. Click ActionsConditions/Loops and then double-click elseif. Like the if action, the elseif action has only one parameter: Condition. 4. Enter the condition that must be true for the associated action to occur. 5. Create the code that executes if the condition is true. 6. Repeat Steps 3 through 6 for other possible outcomes to the first condition. 7. When you arrive at the final possible outcome for the first condition, double-click the else action from the Conditions/Loops book. 8. Enter the condition that must be true in order to execute the associated action. 9. Enter the actions that you want to execute when the condition in the else statement evaluates as true. Listing 8-10 shows an example of the elseif and else actions used to display different messages depending on how well or poorly a player scored on a current events quiz.
In the above example, the first statement checks to see if the player scored below 70. If the condition evaluates as false, the condition in the first elseif statement is evaluated. The Flash Player continues evaluating the possible outcomes until a conditional statement evaluates as true. If none of the elseif statements are true, the else statement takes control. The else statement is the last possible outcome; therefore, no parameters are required. If all conditions evaluate as false, the next line of code executes.
158
When you use a logical operator, you insert it between the statements youre comparing. In the case of the NOT logical operator, you insert if before the condition you want to evaluate. Listing 8-11 shows the correct syntax for the logical operators.
In the above example, the first statement evaluates as true if the password AND the username are correct. The second statement evaluates as true if the password OR the username are correct. In the third example, the statement evaluates as true if an
159
incorrect password is entered and a Boolean statement preceding the code defines what the contents of the password variable must be for the password to evaluate as true. You can create a statement that evaluates more than two conditions by placing the appropriate logical operator for your script between the conditions you want Flash to evaluate.
In the previous listing, if the password is Bill, the variable passed is assigned the Boolean value of true. The next line of code evaluates checks to see if passed has a value of true. If so, the movie advances to a frame labeled Enter, and Bill is granted permission to visit the Web site. If the password is not equal to Bill, the statement evaluates as false and passed evaluates as false; the visitor sees a message instead of gaining entry to the site.
160
Open up this chapters folder on the CD-ROM that accompanies this book and copy the rndQuote.fla and quotes.txt files to your hard drive. Use your operating system to disable the files read-only attribute.
To begin the project: 1. Launch Flash and open the rndQuote.fla file. 2. Open the document Library and double-click the Random Quote movie clip. The clip opens in symbol-editing mode. Notice you have two layers to work with: Text and Actions. The Actions layer has three keyframes. 3. Click the first frame on the Actions layer and then open the Actions panel. 4. Click ActionsVariables book and double-click set variable to add the action to your script. 5. In the Variable field, type rndQuote. 6. Place your cursor inside the Value field and in the left pane of the Actions panel, click ObjectsCoreArray. 7. Double-click newArray to add it to the script. The code newArray() appears in the value field. Your cursor blinks between the parentheses. 8. Minimize Flash, open your word processing software, and open the quotes.txt file you copied to your hard drive. 9. Select all of the text and copy it to the clipboard. 10. In Flash, place your cursor between the parentheses after newArray and right-click (Windows) or Ctrl+click (Macintosh) and choose Paste from the context menu. 11. Click the Expression checkbox. The array is now populated with 70 quotes. In the next section, youll be creating the code to generate the random number. Leave the Actions panel open youll need it again in a minute or so.
161
162
Figure 8-6: In the first frame, you create the array and generate the random number.
To add the timer and access the array: 1. Click the second keyframe on the Actions layer. 2. Open the document Library and drag the timer component on Stage. Place it anywhere it wont be seen when you publish the movie. 3. With the timer component still selected, open the Property inspector and click the Parameter tab. Notice you have one parameter displayed in the window, seconds. To the right of the word seconds, you see the number 10. 4. Double click the 10, enter 3, as shown in Figure 8-7. and press Enter or Return. The timer is now programmed to pause on the frame for three seconds. If thats too much or too little time for your taste, you can change the value at any time. 5. Close the Property inspector, click the second frame on the Actions layer, and open the Actions panel. 6. Click ActionsVariables and then double-click set variable. 7. In the Value field, type quote. This is the same name as the variable in the dynamic text box that is already created for you. When the movie is published, the value of the variable youre now creating is displayed in the dynamic text box. 8. In the Value field, type rndQuote[rndNum]. The first part of the variable value, rndQuote, is the name of the array you created in the first keyframe. The brackets are used to designate the number of the array element (offset). The element offset is the value of the rndNum variable, a random number between 0 and the length of the array.
163
9. Click the Expression checkbox. 10. Click the third frame on the Actions layer. The code in Listing 8-13 has already been created for you. 11. Click the Back button to exit symbol-editing mode.
The code in Listing 8-13 checks to make sure the last random number is not duplicated. A new variable currentNum is set equal to the value of rndNum, the last random number generated. The second line of code generates a new random number using the same code as you created on the first keyframe. The conditional statement in the third line of code checks to see if the new random number is the same as the old one. If the condition evaluates as true, a new random number is created by multiplying the previous random number by the random method of the Math object. Granted, the new number could be the same as the old, but with an array of 70 elements, the odds are against it. The last line of code loops the movie clip to the second keyframe and displays another quote.
164
The finished product may seem a little bland. After all, theres nothing but text on Stage. But this little gem is stored in a movie clip, which means the ActionScript is modular, you can use it in any other movie by using the Open as Library command to open this library and then transfer the movie clip to another document. When you use the Random quote movie clip in another document, you bring the timer right along with it. As a matter of fact, the timer is modular as well. When you use the Random quote movie clip in another document, you can modify the contents of the array to suit the movie. For example, if you have a client who wants to display customer quotes in the header of the Flash movie you are designing, heres the perfect way to do it. After the customer supplies you with the quotes, replace the quotes currently in the array with your clients quotes. You can modify the amount of time each quote is displayed by changing the seconds parameter of the timer component. If need be, you can modify the font style and color by changing the parameters of the dynamic text box that displays the quote.
CrossReference
Designer Notes
In this chapter, you learned to work with variables and arrays. The project at the end of the chapter demonstrates the amount of power you can add to your designs with variables and arrays. When you add arrays to your designs, you can pack an impressive amount of data into a small package. When you take it one step further and put all your code in a movie clip, you can use the movie clip in another document and modify it to suit the design. In the next chapter, you take your knowledge of ActionScript to the next level by using variables and expressions to modify the properties of objects.
III
In This Part
Chapter 9 Generating ActionScript to Modify Objects Chapter 10 Designing Interactive Navigation Chapter 11 Composing Dynamic Text Chapter 12 Building Interactive Interfaces Chapter 13 Creating ActionScript Sound Objects Chapter 14 Debugging an ActionScript
C H A P T E R
In This Chapter
Modifying object properties Changing object opacity Using the Color object Using the Key object Duplicating an object Chapter project: Creating an interactive animation
our previous Flash work probably featured some interesting animations using motion and shape tweening. The problem with motion and shape tweening is that after a while, the results are fairly predictable. Veteran Web surfers have seen a zillion Flash movies and tend to become a bit jaded. If a Web page doesnt jump up and grab them by the throat, they click the Back button and meander elsewhere. You can take your designs to a higher plateau when you use ActionScript to modify the properties of objects in your designs. Instead of creating plain-Jane, me-too Flash designs, you can use ActionScript to create compelling designs that capture the attention of your audience and leave them wanting more. When you place a graphic symbol in a movie clip, you can modify the properties of the object. You can make the object move on demand, create random motion, change the color of an object, scale an object, and vary its opacity. In this chapter, you learn how to modify many object properties. You also learn how to create a Color object. When you create a Color object, you can use it to modify the color of objects. Finally, I show you how to create code that modifies an objects properties with keystrokes from the users keyboard.
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
168
When you change an objects properties using the with action or by directly addressing the objects target path, you use the Properties book to locate the properties you add to your script. If you use either of these methods, you can access the target path using the Insert Target Path dialog box. Remember, you can assign ActionScript only to a named instance of a movie clip, and all named instances in your movie are listed in this dialog box. The third method is probably the simplest you get the objects target path and the property and assign the value with a single action. However, this method is also the most time consuming if you have several properties to change. The method you use to modify an objects properties depends on how comfortable you are, or how comfortable you plan to be, with ActionScript. Table 9-1 lists the properties you can modify with a brief description of each and the parameters you can modify, along with the properties you use to return a the current property of an object, such as the frame number the playhead is over in a movie clip.
169
_currentframe _droptarget
Returns the frame number currently being played Returns the absolute path of an object in slash (\) where a dragged movie clip is dropped A Boolean value that specified whether a movie clip has a yellow rectangle around it when it has keyboard focus Returns the number of frames loaded from a streaming movie An instances name An objects height in pixels Render quality Degree of rotation Time before a movie begins to stream Returns the target path of the specified movie clip Returns the total number of frames in a movie clip Returns the URL of the .swf file from which the movie clip is downloaded Toggles visibility on or off An objects width in pixels An objects x position Returns the current x coordinate of the mouse An objects x scale An objects y position Returns the current y coordinate of the mouse An objects y scale
_focuserect
True or false
_framesloaded _name _height _quality _rotation _soundbuftime _target _totalFrames _url _visible _width _x _xmouse _xscale _y _ymouse _yscale
None, read only None, read only Any numeric value Low, medium, high, best Any value between 0 and 360 An integer None, read only None, read only None, read only True or 1 (visible); false or 0 (invisible) Any numeric value Any numeric value None, read only Any numeric value Any numeric value None, read only Any numeric value
170
It is possible to enter a value for many of the properties in the preceding table that is acceptable to the Flash Player but not realistic. For example, you can enter a value for an objects _x property that moves it beyond the boundaries of the Stage.
Figure 9-1:
171
172
You can also create code that changes an objects property by a certain increment or decrement every time a button is clicked or a key is pressed. You can use this technique to create an interactive animation where the user can move objects with button clicks or key presses. To create an expression that changes an object property by a given value: 1. Select the object or keyframe that triggers the property change. 2. Click ActionsMiscellaneous Actions and then double-click evaluate. One parameter text box named Expression appears. 3. Enter the target path of the object you want to apply the property change to. 4. Type a dot ( . ) after the targets name. 5. Enter a plus sign (+) to increase (increment) the value of the property or a minus sign () to decrease (decrement) the value of the property. 6. Type an equals sign (=) followed by the amount you want to increment or decrement the property by. Figure 9-2 shows the Expression field and several lines of code where an objects property is incremented or decremented by a set amount. You can also use a variable for the value. When you use a variable for a value, you can modify the variable to change the amount the property is incremented of decremented by. For example, you can speed up an object by increasing the value of a variable when a key is clicked.
Figure 9-2:
173
You can get an objects property using two methods. You can address the object directly by referring to its target path, or you can use the getProperty function. The resulting code for both methods is shown in Listing 9-3.
Both examples in the previous listing retrieve the same result. When you get an objects property, you set it equal to a variable so that as the property changes, the value of the variable also changes. To address the clip directly by its path, do the following: 1. Select the object or keyframe where you want the action to occur. 2. Click ActionsVariables and then double-click set variable. 3. In the Variable field, enter a name. Choose a name that reflects the property you are retrieving. In the previous example, the variables value is equal to _y property of the movie clip, hence the name yPos. 4. Click inside the Value field, click the Insert a Target Path button, and from the Target Path dialog box, click the button that corresponds to the movie clip you whose property you want to use in your script. Then close the Insert Target Path dialog box. 5. In the Value field, type a dot ( . ) to the right of the target path.
174
6. Enter the property you want the variable to return. In the above example, the sphereClips _y property is returned by the yPos variable. If youre not sure of the proper syntax for a property, position your cursor to the right of the dot, open the Properties book, and then double-click the property you want the variable to return. You can also use the getProperty function to return the value of an objects property. This function is not as easy to use as the setProperty action because the getProperty function does not have object properties listed on a menu. Youll probably find it easier to address the movie clip target directly and then choose the desired property from the Properties book (as outlined in the previous steps). If you prefer to use the getProperty function, follow these steps: 1. Select the object or keyframe where you want the action to occur. 2. Click ActionsVariables and then double-click set variable. 3. In the Variable field, enter a name that reflects the type of property the variable is returning. 4. Click inside the Value field and in the left pane of the Actions panel, click Functions and then double-click getProperty. The function is added to your script and the Value field getProperty() appears. 5. Place your cursor between the parentheses and click the Insert a Target Path button to add the movie clips target path to the script. 6. To the right of the movie clips path, type a comma and then enter the property you want the variable to return. If youre not sure of the syntax, in the left pane of the Actions panel, click Properties and then double-click the applicable property. Figure 9-3 shows a variable whose value is set using the getProperty function to return an objects property.
Figure 9-3:
175
176
object and then transform them. You use the setRGB method to modify a solid color and the setTransform method to tint a multi-colored object such as a bitmap image or a vector object with a gradient fill.
If youre not sure of the hexadecimal value of the color you want to apply, choose WindowColor Mixer to open the Color Mixer panel. Click the swatch in the Fill Color well and choose a color from the palette. If you work with the Color Mixer expanded to show all windows, the hexadecimal value of the selected color is displayed below the Color Sample window.
5. Click the Expression checkbox. When the movie is published and the event to trigger the setRGB method occurs, the object will be changed to the colors specified.
CrossReference
177
of parameters. You use four of the parameters to vary the percentage of red, green, blue, and alpha in the original color, and four sets of parameters to specify the offset values of the original color. The offset values for the red, green and blue components correspond to the 8-bit, 256-color model. Each of the parameters is described in the following list: ra: Specifies the percentage to change the red component. Acceptable values are from 100 to 100. rb: Specifies the amount to offset of the red component. Acceptable values are from 255 to 255. ga: Specifies the percentage to change the green component. Specify a value from 100 to 100. gb: Specifies the amount to offset the green component. Specify a value from 255 to 255. ba: Specifies the percentage to change the blue component. Use a value between 100 and 100. bb: Specifies the amount to offset the green component. Use a value between 255 and 255. aa: Specifies the percentage to change the alpha component. Acceptable values are from 100 to 100. ab: Specifies the amount to offset the alpha component. Acceptable values are from 255 to 255. It may help to think of these changes as before and after. The percentage values modify the values in the original color. They either add or remove a percentage of the component. This is similar to adjusting an objects color characteristics in an image editing program such as Photoshop. The offset values are the equivalent of tinting an object. For example, if you specify a value of 255 for the rb setting, its the equivalent of applying a red tint over an object.
Tip
Before you decide on what settings to use with the setTransform method, select the movie clip and open the Property inspector. Click the triangle to the right of the Color field and choose Advanced from the drop-down menu. Click Settings to open the Advanced Effect dialog box. Drag the sliders in the two columns until you have the desired transformation. Jot the percentage figure for each component in the left window. They correspond to the ra, ga, ba, and aa parameters. Write down the offset values from the right column. These correspond to the rb, gb, bb, and ab settings. After getting the values, be sure to choose None from the Color field as you want to use ActionScript to transform the color. The Advanced Color effect will yield a larger file size than if you apply the change with ActionScript.
When you use the setTransform method to tint a bitmap, you need to create a new object. The object passes the transformation data to the Color object.
178
To tint an object with the setTransform method, do the following: 1. Create a Color object as previously outlined. 2. Click ActionsVariables book and double-click set variable. 3. In the Variable field, enter a name for the color transformation object. A logical choice is myColorTransformation. 4. Click inside the Value field and then in the left pane of the Actions panel, click ObjectsCoreObjects. 5. Double-click newObject. After you create the color transformation object, you need to specify the parameters for the transformation. There are two different ways to do this. You can specify each parameter individually by creating an expression. This is handy when youre just modifying one or two parameters. For example, to apply a light blue tint to a bitmap, you need to use only the bb parameter. If youre modifying all the parameters, you create a single expression. The following list shows both ways of specifying the parameters for a transformation. The last item on the last specifies a value for each parameter, while the other items address a single parameter. myColorTransform.ra=75 myColorTransform.rb=175 myColorTransform.ga=25 myColorTransform.gb=215 myColorTransform.bb=65 myColorTransform.bb=240 myColorTransform.aa=-52 myColorTransform.ab=15 myColorTransform={ ra: 80, rb: 204, ga: 30, gb: 212, ba: 12, bb:90, aa: 40, ab: 70} 6. Click ActionsMiscellaneous Actions book and then double-click evaluate. The Expression parameter box appears (see Figure 9-4). 7. In the Expression field, type myColorTransform and then use one of the methods outlined in Step 5 to set the parameters. You address individual parameters by typing a dot ( . ) after the parameter followed by an equals sign (=) and then the value. If you use the last method outlined in Step 5, enter the equals sign (=) and then curly braces. Between the curly braces, list each parameter is followed by a colon and the parameter value, which is enclosed in single quotes.
179
8. Click ObjectsMovie bookColor bookMethods book and then double-click setTransform. The action is added to the script and two parameter text boxes appear above the Script pane. 9. In the Object field, enter the name of the Color object linked to the movie clip youre transforming. 10. In the Parameters field, enter the name of the color transformation object you created in Step 7. When the movie is published and the event that triggers the code occurs, the object is transformed to the parameters of the color transformation object. Figure 9-5 shows a typical script using the setTransform method. Figure 9-6 shows four bitmaps. The original is in the upper-left corner; the other three have been transformed using the setTransform method.
Figure 9-4:
On the CD-ROM
In this chapters folder on the CD-ROM, youll find a file called colorComponents.fla. Open the document Library and youll find two components. You can add the setRGB component to a movie clip that includes a graphic with a solid fill. After adding the component to the movie clip, open the Property inspector and click the color swatch to specify the color you want the object to change to. You can use the setTransform component in a movie clip that has a bitmap object whose color characteristics you want to modify. If you use the component more than once in a document, give each instance a unique name.
180
Figure 9-5: You can achieve some interesting effects by modifying an objects color properties.
181
object, you can use multiple keys for your ActionScript. You can address each key by its key code or take the easy way out and use one of the constants that addresses most of the popular keys youd use in ActionScript, for example the arrow keys, Page Up, Page Down, spacebar, and so on. You can use the Key object with other actions on a keyframe; however, you need to loop back and forth between two keyframes. If you dont loop back and forth, Flash will execute the action once when the keyframe is reached and not read additional key presses. A better way to use the Key object is with a single-frame movie clip using the onFrameEnter event. Flash executes the script every time the frame is entered. To use the Key object in a script, do the following: 1. Select the object or keyframe that you want to use to trigger the script. Your best bet is to use a movie clip and use the onEnterFrame clip event. 2. Click ActionsConditions/Loops and double-click if. The action is added to your script and the Condition parameter text box opens. 3. Click ObjectsMovieKeyMethods and double-click isDown. The text Key.isdown() appears in the Condition parameter box and your cursor flashes between the parentheses. 4. In the left pane of the Actions panel, click ObjectsMovieKeyConstants and then double-click the key you want to trigger the actions that follow. 5. Create the code you want to execute when the key is pressed. The code in Listing 9-4 makes it possible for the user to navigate the movie clip the code is assigned to by clicking one of the arrow keys. Notice that an expression has been used to increment or decrement the objects _x or _y property. By pressing the two of the arrow keys that trigger the objects movement in different axes, diagonal movement occurs.
182
You can create additional statements that rotate the object if, for example, the right and up arrow keys are pressed at the same time.
183
Figure 9-6: You create duplicates of an object with the duplicateMovieClip action.
Locate the submarine.fla file in this chapters folder on the CD-ROM that accompanies this book. Copy the file to your hard drive and use your operating system to disable the files read-only attributes.
In this project, youll be animating a submarine (see Figure 9-7) by creating code that checks for a key press. The arrow keys will be used to navigate the submarine. You wont be creating each and every line of code. Much of the script has been written for you. You will create a conditional statement that checks for a key press and moves the sub in a specific direction. To create an interactive animation: 1. Launch Flash and open the file submarine.fla. The file consists of a solitary submarine on a sea bottom.
184
2. Select the submarine and open the Actions panel. You see several lines of code have been created for you. Notice that the first lines of code use the load clip event. This initializes the variable speed. The next several lines of code check to see if one arrow key is pressed and the opposite arrow key is not pressed. This code determines the direction and rotation of the submarine. Youll be creating a few lines of code to move the submarine towards the top of the Stage. 3. Place your cursor over the line of code that reads // Check for keys that
are pressed, set direction and rotation.
4. Click ActionsConditions/Loops book and double-click if. 5. Place your cursor in the Condition field, and in the left pane of the Actions panel, click ObjectMovieKeyMethods and then double-click isdown. The action is added to your script and in the Conditions field, your cursor is flashing between parentheses. 6. In the left pane of the Actions panel, open the Constants book and doubleclick UP. The words Key.Up appear between the parentheses. 7. In the Conditions field, click to the right of the parenthesis, type a space and then type && ! You may recognize the double ampersand (&&) as the logical AND operator from Chapter 8. The single exclamation point is the Logical NOT Operator. It checks for the reverse of the next condition in the statement. 8. In the left pane of the Actions panel, ObjectMovieKeyMethods doubleclick isdown. 9. In the left pane of the Actions panel, click ObjectMovieKeyConstants and then double-click Down. (At this point, you may find it convenient to close one or two of the books to make navigating the Actions panel a bit easier.) 10. Click ActionsMiscellaneous Actions and double-click evaluate. The Expression pane appears above the Script pane. 11. In the Expression field, type the following code: _y- = speed This line of code decrements the _y property of the movie clip by the value of the variable speed. 12. In the Script pane, click the line of code you just created. 13. In the left pane of the Actions panel, double-click evaluate.
185
14. In the Expression field, type the following code: _rotation = 0 This line of code sets the rotation of the sub to 0 degrees when the up arrow key is pressed. Your finished code should look like this:
if (Key.isDown(Key.UP) && !Key.isDown(Key.DOWN)) { _y -= speed; _rotation = 0; }
15. Close the Actions panel and then choose ControlTest Movie. After Flash publishes the movie and opens it in another window, press any of the arrow keys to set the sub in motion. After the sub is moving, press the right arrow key and the up arrow key. Notice that the sub veers to the right. When the sub moves beyond the range of the movie, it pops out on the other side. The subs moving at a snails pace, though. Press the Shift key to kick it into overdrive; press the spacebar to slow it back down again. After youre finished navigating your yellow submarine, save your work and study the complete code for the movie clip, as shown in Listing 9-6.
Figure 9-7:
186
187
} if (_y>435) { _y = 5; } // Increases and decreases sub speed if (Key.isDown(Key.SHIFT)) { speed = 7; } if (Key.isDown(Key.SPACE)) { speed = 2; } }
As you study the above listing, youll see several comments (the text preceded by two forward slashes) that explain what the following lines of code accomplish. All of the code that sets the sub in motion follows the enterFrame clip event. When you use the enterFrame clip event with a single frame movie clip, Flash continually reevaluates the code that follows.
Designer Notes
In this chapter, you learned to modify objects by changing their properties. Modifying an objects color characteristics was another key topic in this chapter. You were introduced to the duplicateMovieClip action, which youll use in upcoming chapters to create eye candy for your Flash designs. You also learned to generate action after a key is pressed. The chapter project combined your knowledge of conditional statements with the Key object to create an interactive animation. In the next chapter, you learn to work with dynamic and input text objects.
10
C H A P T E R
In This Chapter
Breaking a movie into scenes Working with named anchors Creating a navigation bar Designing an On When Pressed button Creating an animated button Chapter project: Creating a flyout menu
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
Navigating to Scenes
When you create a movie that uses an introduction before the main movie, you can save yourself a lot of time by breaking the movie into scenes. Breaking a movie into scenes makes it easier to find objects, especially if you end up adding a lot of
190
frames to the design. If the movie is large enough to warrant a preloader, thats yet another reason to break the movie into scenes. If the movie has a logical beginning, middle, and end (meaning, for example, an introduction, the main movie, and an exiting trailer), break the movie into three scenes. If youve created a particularly compelling introduction, you can create a button to replay the introduction. You can break a movie into scenes like youd break a Web design into separate pages. Create a separate scene for each section of the movie and create a navigation menu viewers can use to navigate from scene to scene.
Adding a scene
You can add a scene to a movie at any time. When you add a scene to a movie, youve got a blank Stage and a single timeline with one keyframe. Consider adding a scene whenever you reach a logical breaking-off point or if the sheer magnitude of frames is more than youre willing to deal with on one timeline. To add a scene to your movie: do one of the following: 1. Choose InsertScene. A new scene is added to your movie. 2. Choose WindowScene to open the Scene panel shown in Figure 10-1 and then click the Add Scene button that looks like a plus sign (+).
Figure 10-1: You can create separate scenes for your designs.
Naming a scene
When you add a scene to a movie, it is given the default name of Scene followed by the next available number. While this is perfectly logical, the name is not very intuitive, especially if youre working with other designers. Whichever way you go about adding a scene to a movie, you use the Scene panel to name it. To name a scene: 1. Choose WindowScene. 2. Double-click the scene name. A text box appears and the current scene name is highlighted. 3. Type a new name for the scene and press Enter or Return.
191
Navigating to a scene
After you have a movie divided into scenes, you can quickly navigate from one scene to another as needed. There are three methods you can use to navigate to a scene. To navigate to a scene, do one of the following: Choose ViewGo To and choose a scene name from the submenu. Choose WindowScene to open the Scene panel and then click the scene name. Click the Scene button (looks like a movie clapper) and select a scene from the menu, as shown in Figure 10-2.
Scene button
Scenes in movie
Figure 10-2: You can navigate to a scene by choosing it from this menu.
Deleting a scene
After you break a movie into scenes, you may find a scene is no longer needed. You can delete a scene at any time. You can delete a scene in one of two ways.
192
To delete a scene: Navigate to a scene and then choose InsertRemove Scene. Choose WindowScene to open the Scene panel. Select the scene name and then click the Delete button, which looks like a trash can. After you choose to delete a scene, you are prompted to confirm the deletion. Click OK to delete the scene from your design.
Duplicating a scene
You can duplicate a scene when it becomes necessary to create a new scene with elements from the preceding scene. This option is useful when, during the planning stage of your design, you decide to break a movie into scenes. Create the main scene with all the elements that will be used in every scene; for example, the movies banner and navigation buttons. Duplicate the scene as needed and change the scene name to reflect what the scene does. Remember, you can use the scene name when creating ActionScript for navigation. Remembering a unique scene name is easier than remembering which scene number the navigation button needs to link to. To duplicate a scene, do the following: 1. Choose WindowScene to open the Scene panel. 2. Select the scene you want to duplicate. 3. Click the Duplicate Scene button. 4. Name the scene. 5. Close the Scene panel.
193
194
2. Click the HTML tab to open the HTML section of the dialog box. 3. Click the triangle to the right of the Template field, and from the drop-down menu, choose Flash with Named Anchors (see Figure 10-3).
Figure 10-3: You must choose the proper template to activate named anchors.
195
4. Enter a name for the symbol, choose the Movie Clip behavior, and then click OK to enter symbol-editing mode. 5. Open the document Library and drag an instance of the button symbol you created in Steps 1 and 2 into the movie clip. 6. Center the button to Stage using the Align panel. 7. With the button still selected, click the arrow to the left of the word Actions. 8. In the left pane of the Actions panel, click ActionsVariables and then doubleclick set variable. 9. In the Variable field, type clicked. 10. In the Value field, type true and click the Expression checkbox. 11. Click the first line of code to select it and change the event handler to Press. 12. Repeat Steps 8 through 10 using the set variable action to set the value of clicked to false. Accept the default release event handler. Your code should look like Listing 10-1. 13. Click the Back button to return to movie-editing mode.
The code in Listing 10-1 sets the value of clicked to true as long as the button is pressed. When the button is released, the value of clicked is false. To finish creating an On When Pressed button, you program the movie clip the button is nested in. To program the movie clip, you use a conditional statement. A conditional statement evaluates a statement, and if the condition is true, executes the code that follows. If the statement evaluates as false, the next bit of code executes. To program the movie clip, do the following: 1. Click the arrow to the left of the word Actions. 2. In the left pane of the Actions panel, click ActionsConditions/Loops and double-click if. The action is added to your script and the Condition field appears above the Script pane.
196
3. In the Condition field, type clicked. Thats all thats needed. You dont have to create a statement like clicked=true. Flash knows that the clicked variable is a Boolean expression. To create a statement to evaluate if the button isnt clicked, you use the Logical NOT operator discussed in Chapter 9 and create a statement that reads !clicked. 4. Create the code that executes when the button is clicked. 5. Click the first line of code and choose the EnterFrame clip event. When you choose the EnterFrame clip event, Flash executes the code in the movie clip every time the frame is entered, which is just what you want. When the user presses the mouse button and holds it down, the script is executed until the button is released, upon which time the Boolean value of clicked is false. Listing 10-2 shows a script that continually scrolls a block of text while a button is clicked. Youll be creating a scrolling text box in Chapter 11.
197
198
7. Create additional frames for the other button states you want to use. 8. Modify the color and fill of the button shape for the other button states. 9. To modify the color of the label symbol, open the Property inspector, click the triangle to the right of the Color field and choose Tint. Click the color swatch and select a color from the pop-up palette. Now that you have the first button created, you can quickly create the rest of the buttons for your navigation bar by doing the following: 1. Open the document Library. 2. Select the button symbol you just created. 3. Click the Options menu icon in the upper right corner of the Library panel and choose Duplicate. Alternately, you can right-click (Windows) or Ctrl+click (Macintosh) and choose Duplicate from the drop-down menu. 4. In the Duplicate Symbol dialog box, enter a name for the symbol. Choose a name that matches the buttons title, for example, servicesButton. 5. Create one duplicate for each button on your navigation bar. 6. After you duplicate the buttons, double-click each button to enter symbolediting mode. 7. Select the label symbol, open the Property inspector, and click the Swap button to open the Swap Symbol dialog box (see Figure 10-4).
Figure 10-4: You can quickly swap the label symbol with another from the document Library.
8. Select the appropriate label symbol for this button and click OK to swap the symbol. If you created additional states for the button, select the keyframe, select the symbol, and swap it. When you swap a symbol, any effect you applied to the previous symbol is inherited by the new symbol. 9. Continue in this manner until you have swapped the label symbol for all duplicated buttons.
199
Swapping symbols is an easy way to quickly create several buttons. Instead of creating the shape for each button and then creating the text, you create the button shape one time, duplicate the button, and swap the label. If you need to use the label symbol in other parts of the movie, just drag an instance of it on Stage and modify it to suit.
Figure 10-5: You can quickly create a navigation bar by duplicating a button symbol.
To learn how to create an animated button with ActionScript, copy to your hard drive the file Jittery.fla from this chapters folder on the CD-ROM that accompanies this book. Use your operating system to disable the files read-only attribute.
200
201
anew. When you use ActionScript to animate an object, the change is instantaneous, meaning that it happens as soon as the actions execute. You can add a few frames after the second frame to display the label with its changed properties, or you can pause the movie at the frame for a random amount of time. (You do the latter by adding a user-defined timer component to the second frame that pauses the movie for a random amount of time.) To animate the label: 1. Select the first keyframe and then click the triangle to the left of the word Actions. 2. In the left pane of the actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. The Expression field appears above the Script pane. 3. In the Expression field, type the following: Jitter._xscale=100 This line of code sets the _xscale property of the movie clip Jitter to 100 percent. You dont have to specify a target path for the movie clip as it is nested within the movie clip youre creating the ActionScript in. 4. Repeat Step 3 to set additional properties as shown in Listing 10-3.
5. Select the second keyframe. 6. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. 7. In the Expression field, type the following code: Jitter._xscale+=Math. random()*75. This line of code adds a random value between 0 and 75 to the _xscale property of the movie clip Jitter. As you may remember, the random method of the Math object generates a random number between 0 and 1. Multiplying the result of the random method by another number generates a random value between 0 and that number. Now that youve modified the _xscale, you can modify other properties to animate the movie clip. 8. Repeat Step 7 to modify the _yscale, _x, and _y properties of the movie clip, as shown in Listing 10-4.
202
Listing 10-4: Creating the Code to Change the Movie Clips Properties
Jitter._yscale+=Math.random()*75; Jitter._x+=Math.random()*3; Jitter._y+=Math.random()*3;
The only property you havent modified is the movie clips rotation. You can modify the rotation property by a given number of degrees to make the movie clip rotate, but it will rotate in only one direction. To get the movie clip to rotate clockwise and counterclockwise, you create a conditional statement. 9. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click if. The Condition field appears above the Script pane. 10. In the Condition field, type the following: Jitter._x<1.5 11. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. 12. In the Expression field, type the following: Jitter._rotation+=Math.random()*15 13. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click else. 14. In the left pane of the Actions panel click ActionsMiscellaneous Actions and then double-click evaluate. 15. In the Expression field, type the following: Jitter._rotation-=Math.random()*15 Your code for the conditional statement should look like Listing 10-5 The conditional statement you just created checks to see if the value of the movie clips _x property is less than 1.5. When it is, the _rotation property of the movie clip is incremented by a random value between 0 and 15; in other words, the movie clip rotates in a clockwise direction. If the value is greater than 1.5, the _rotation property decrements by a random value between 0 and 15, rotating the movie clip in a counterclockwise direction.
203
16. Choose WindowLibrary to open the document Library. 17. Drag the timer component anywhere on Stage. 18. Click the arrow to the left of the word Properties to open the Property inspector. 19. In the Pause for: field, enter a value of .3 The component you just added to the movie clip will pause the movie on the frame for a random amount of time equal to or less than the value entered in the Pause for: field. 20. Select the third keyframe. 21. In the left pane of the Actions panel, click ActionsMovie Control and then double-click goto. Accept the default parameters to go to and play frame 1. 22. Click the Back button to exit symbol-editing mode. After you exit symbol-editing mode, the symbol is added to the document Library. To finish creating the animated button, you nest the movie clip in a button symbol.
204
9. Drag an instance of the button on Stage and then choose ControlTest movie. After the movie is published, roll your mouse over the button. The label should start randomly moving around. When you roll off the button, the motion stops. If the motion wasnt frenetic enough for your tastes, edit the jitteryClip and change the value in the timer components pause for field. Note that the actual object being animated is a symbol. By duplicating the movie clips and button, and then swapping symbols, you can quickly create additional animated buttons.
To create the flyout menu project, copy to your hard drive the flyoutMenu.fla file from this chapters folder on the CD-ROM that accompanies this book. Use your operating system to disable the files read-only attribute.
1. Launch Flash and open the flyoutMenu.fla file. The document contains a navigation bar and a Menu button, as shown in Figure 10-6. If you were creating your own flyout menu, at this stage youd have each button programmed with the exception of the ActionScript needed to activate the flyout menu. 2. Click the arrow to the left of the word Actions. After the Actions panel opens, click the scroll bar to the right of the Stage and drag it so that both the Actions panel and the buttons are visible, as shown in Figure 10-7. 3. Select the Services button and in the left pane of the Actions panel, click ActionsMovie Control and then double-click play. The default release event is added to the script. 4. Select the three lines of code and then right-click (Windows) or Ctrl+click (Macintosh) and select Copy from the context menu. 5. Click the Listings button and then in the Script pane, right-click (Windows) or Ctrl+click (Macintosh) and select Paste from the context menu. 6. Repeat Step 5 to paste the code to the other buttons.
205
Figure 10-6: You can convert a navigation bar into a flyout menu.
The previous steps demonstrated how you can save time when you need to use the same code on several objects. Now that youve programmed the buttons, its time to convert the navigation bar into a symbol. To convert the navigation bar to a symbol, do the following. 1. Select the buttons on the navigation bar. 2. Choose InsertConvert to Symbol. The Convert to Symbol dialog box opens. 3. Enter a name for the symbol, choose the Movie Clip behavior, and click the center left square for the registration point, as shown in Figure 10-8. This sets the symbol registration point equal the left side of the buttons, which makes it easier to manipulate the position of the buttons with the Property inspector because the x, y coordinates in symbol-editing mode are the same as the x, y coordinates of the Stage. 4. Click OK to convert the buttons into a symbol. At this stage the new symbol is added to the document Library. It should also be selected on Stage. 5. Choose EditEdit in Place. The workspace is converted to symbol-editing mode.
206
Figure 10-7: You can save time by copying code from one button and pasting it to another.
207
6. With the buttons still selected, choose ModifyDistribute to layers. A separate layer is created for each button. Each layer has the same name as the button within the layer. Select Layer 1 and rename it to Actions. 7. Select the buttons, open the Property inspector, and type 600 in the X: Field. This moves the buttons to the left of the Stage, exactly where you want them to appear when the movie begins playing. 8. Press Ctrl (Windows) or (Macintosh), click frame 12 in the Actions layer, and drag down to select frame 12 in all layers. 9. Press F6 to convert the frames to keyframes. 10. Click the first frame in the service layer and then drag down to select all of the button layers. 11. Choose InsertCreate Motion Tween. A motion tween arrow appears between the beginning and ending keyframes on each button layer. 12. Click the sixth frame in the Actions layer, press Ctrl (Windows) or (Macintosh) and drag down to select all the frames. 13. Press F6 to convert the frames to keyframes. All the buttons will be selected. 14. Open the Property inspector, click the About button and change the value in the X: Field to 0. The buttons are moved to their flyout position, as shown in Figure 10-9. This sets up the basic animation for the buttons. When the movie initially begins, the buttons are not visible. When the flyout menu is activated, the buttons move to the left side of the movie.
15. Click the first keyframe in the Actions layer, and then click the arrow to the left of the word Actions. 16. In the left pane of the Actions panel, click ActionsMovie Control and then double-click stop. 17. Repeat Step 16 for the sixth frame in the Actions layer.
208
18. Select the 12th frame in the Actions layer and open the Actions panel. 19. In the left pane of the Actions panel, click ActionsMovie Control and then double-click goto. 20. Click the Go to and Stop radio button. Accept all the other parameters. 21. Click the Back button to exit symbol-editing mode. 22. Click the arrow to the left of the word Properties to open the Property inspector. 23. Type menu in the <Instance Name> field. 24. Click the Menu button in the upper-right corner of the document. 25. Click the arrow to the left of the word Actions. The Actions panel should read Actions-Button. If it doesnt, select the button again. 26. In the left pane of the Actions panel, click ActionsVariables and then doubleclick with. 27. Click the Insert a Target Path button to open the Insert Target Path dialog box. 28. Click the button labeled menu and then click OK to add the target path to the script. 29. In the left pane of the Actions panel, click ActionsMovie Control and then double-click play. 30. Choose ControlTest Movie. When you click the Menu button, the menu should fly in from the side of the interface. After the menu flies open, click any of the buttons to retract the menu. In a nutshell, this is how the menu works: When the movie plays, the stop action on the first frame of the menu movie clip prevents the movie clip from playing. When the Menu button is clicked, the play action starts the movie clip, the motion tween moves the buttons into position, and the stop action in frame 6 halts the movie. When you click any button on the navigation bar, the play action starts the movie again and the buttons retract. When frame 12 is reached, the goto action sends the movie to frame 1 where it stops until the Menu button is clicked and the movie clip starts again.
Designer Notes
In this chapter, you learned to add some interactive navigation elements to your designs. You learned how to break a movie down into scenes as well as how to create named anchors for use as browser navigation devices. You learned how to quickly create a navigation bar by duplicating buttons and swapping symbols. The chapter project showed you how to create a flyout menu. In the next chapter youll to use ActionScript with dynamic text.
11
C H A P T E R
In This Chapter
n your previous Flash forays, you probably used text in your designs, possibly even dynamic text. ActionScript and dynamic text make it possible for you to display data that you store in variables. When you combine variables with dynamic text, it is possible for you to change the content of dynamic text boxes. You can use dynamic text boxes to respond to viewer inputs, display data from within a text array, or load data from an external source. Input text boxes, on the other hand, accept input from viewers of your designs. For example, you can use input text boxes to accept information in an e-commerce design such as a users name and shipping address. In this chapter, you learn how to create dynamic text and input text. As for chapter projects, you create a scrolling text box that is populated by data loaded from an external source and also create a scrolling marquee.
Working with dynamic text Creating input text boxes Creating rich formatted text Creating text links Loading text into a movie Chapter project: Creating a scrolling text box Creating text fields
Note
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
210
progresses. (You were introduced to a dynamic text box when you worked through the project in Chapter 7.) You create text with the Text tool and then use the Property inspector to specify whether the text is dynamic text, input text, or static text.
Instance name
Selectable
Variable name
Figure 11-1: You specify text parameters with the Property inspector.
2. Click the triangle to the left of the Text type field and choose Input Text from the drop-down menu. 3. Specify the font size, font type, and font color. 4. Enter a name in the <Instance name> field. Although you cant assign actions to a input text box, you can refer to it from ActionScript in other objects or keyframes. 5. Click the triangle to the right of the line type field and choose one of the following options: Single Line: Displays text as a single line. Multiline: Wraps text to the next line when it exceeds the boundary of the text box. Multiline No Wrap: Wraps text to the next line when the user presses Enter or Return; otherwise, the text exceeds the boundary of the box.
211
Password: Displays each letter entered as an asterisk to prevent the users password from being intercepted by someone nearby. 6. Enter a name in the Var field. If you will be displaying this data in a dynamic text box, use the same name in the dynamic text boxs Var field. Remember to adhere to the variable naming conventions discussed in Chapter 9. 7. Enter a value in the Maximum Characters field. This is the maximum amount of characters the input text box will accept. Users can enter as many characters as they want, but when the user clicks a button to submit the data, the variable assigned to the text box wont accept more data characters than the value you specify in this field. 8. Click the Show Border around Text button. When you choose this option, Flash displays a border around the text when the movie is published. Without a border, an input text box would never be seen by the users, even though their cursors would change to I-beams if they happened to click inside the box. 9. Select the Text tool and drag across to create a text box of the desired length. Drag across to create a text box that accepts a single line of text, or drag down and across to create a text box that accepts multiple lines of text, such as the comments field in an online form. After you set the parameters for an input text box, it is ready to accept data from a user. As you can see by the options, you can use an input text box for quite a few things in your designs. They can be the basis for an online form, much like the one youll work with in Chapter 15. Input text boxes can also be used to password-protect a site. The data entered by the user is evaluated using a conditional statement you create that determines whether the password entered is valid or not. You can limit the type of data entered by the user by changing character options, which is presented before the end of this chapter.
212
3. Specify a font size, font color, font type, and other parameters you want assigned to the text box. 4. If the dynamic text box will be referenced in other ActionScript, enter a name in the <Instance Name> field. 5. Enter a name in the Var field. This is the variable name youll be referring to when you want to display the contents of other variables, or data in this field. 6. Click the triangle to the right of the line type field and choose one of the following: Single Line: Displays a single line of text in the field and does not wrap text when the boundary of the text box is exceeded. Multiline: Displays text as multiple lines, wrapping to the next line when the text exceeds the border of the text box. Multiline No Wrap: Displays text as multiple lines. The Flash Player wraps text to a new line when encountering a hard break character caused by pressing Enter or Return in a word processing program. 7. Click the Selectable button if you want users to be able to select the text displayed in this box. 8. Click the Render as HTML button to render text with HTML tags with rich text formatting options. (You learn how to create rich formatted text in an upcoming section.) 9. Select the Text tool and then drag a text box on Stage. The dynamic text box is now ready to receive data. If you suspect the text you specify may not be available on computers used to view your design, you can embed the fonts with the movie by following the instructions in the next section.
213
Figure 11-2: You can embed an entire font set or a partial font set by specifying character options.
3. Choose to embed the entire font set by clicking the All Characters radio button. To embed a partial font set, click the Only button and choose an option. When you choose to embed a partial font set with an input text box, only the embedded characters are passed on to the variable. This is handy when youre accepting numeric input. Limit the maximum number of characters to 5 and embed only numerals, and in the Include These Characters field, type a decimal point ( .). By doing this, you limit the maximum value the users can input to 99999 with no decimal point, or 99.99 with a decimal point. 4. Click Done to close the dialog box.
214
215
To display rich formatted text in your design, you create a dynamic text box as outlined previously. Click the Render as HTML button and when the movie is published, the formatting specified by the tags is used to display the text. Figure 11-4 shows a published movie with a block of rich formatted text.
Figure 11-4: You can liven up a design by using rich formatted text.
216
217
To create an e-mail link, do the following: 1. Create a document in a word processing program. 2. In the first line of the document, enter the variable name you will assign to the dynamic text box that will display the e-mail link. 3. At the spot where you want the e-mail link to appear in the document, type the following tag: <a href="mailto:[email protected]"> E-mail me</a>. 4. Save the document as a text(*.txt) file. 5. In Flash, create a dynamic text box. 6. In the Var field, enter the same name you used when creating the text file. 7. Click the Render Text as HTML button. 8. Select the first frame of the document and use the loadVariables action to load the text file into the movie as outlined previously. When the movie is published and played in a Web browser, the familiar hand icon appears when viewers roll their mouse over the text link. When the link is clicked, the Web browsers mail program opens a blank e-mail document addressed to recipient specified in the HTML tag.
To follow along with this tutorial, locate the scrollText.fla and scrollText.txt files located in this chapters folder on the CD-ROM that accompanies this book. Copy the files to your computer and use your operating system to disable the files readonly attributes.
To begin the creating scrolling text: 1. Launch Flash and open the scrollText.fla file. Most of the project is completed for you. The document, as shown in Figure 11-5, consists of a banner, two images, and a blank text field. The loadVariables action has already been assigned to the first frame. To the right of the text field is a multi-functional slider. The upper and lower arrows scroll the text. The white bar at the top of the slider can also be dragged to scroll the text. The up and down arrows are buttons nested in a movie clip. The white bar is in a movie clip nested with an invisible button that is coded so that the movie clip can be dragged vertically when the button is pressed.
218
Figure 11-5: You have all the necessary elements to create scrolling text.
2. Choose ControlTest Movie. After Flash publishes the movie and opens it in another window, you see the result of the loadVariables action. The dynamic text field is filled with rich formatted text. Click the white bar and drag down. The text starts scrolling as shown in Figure 11-6. After you scroll to the end of the text, click the up arrow at the top of the slider and hold the mouse button. (This is the same type of button you learned to create in Chapter 10.) Click the down arrow at the bottom of the slider bar, and the text stays still because the button hasnt been programmed yet. Youll be programming this button to scroll the text in just a few minutes. 3. Close the window to return to movie-editing mode.
219
To program the down arrow, follow these steps: 1. Select the Slider layer and then double-click the slider to the right of the text box. After you double-click the symbol, you enter symbol-editing mode. You may find it helpful to zoom in on the slider before continuing. 2. Click the down arrow. The down arrow is a movie clip nested within the symbol. The actual button is nested within the arrow movie clip. This button has two Boolean statements that set the value of the variable clicked to true when the button is pressed, false when the button is released. This is the same code you created when you learned to create a button that is on when pressed in Chapter 10.
220
3. Open the Actions panel. Notice that most of the code is already written for you. Listing 11-2 shows the code already created for you.
The code in the previous listing is executed when the frame is entered. As you learned previously, when you use the enterFrame clip event, the actions that follow are constantly evaluated. You have two conditional statements to work with. You create the code for the first conditional statement, which advances the text one line at a time when the button is pressed while at the same time synchronizing the movement of the slider bar. The second conditional statement prevents the slider bar from moving beyond the boundary of the slider. 4. In the Actions panel, select the second line of code that reads: if (clicked) {. 5. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and double-click evaluate. The Expression text parameter box opens above the Script pane. 6. Place your cursor inside the Expression field and click the Insert a Target Path icon. The Insert Target Path dialog box opens. 7. Click the ScrollBox icon as shown in Figure 11-7 and then click OK. This is the target path to the dynamic text box. 8. In the left pane of the Actions panel, click ObjectsMovieText Field Properties and double-click scroll. The scroll property of the Text Field object reads the current position of the text in the dynamic text box. When the movie loads, the scroll value of the text is 1. As the text scrolls to another line, the scroll value increases by 1. The expression you are creating will increment the value of the Text Field object ScrollBox by a value of 1 as long as the button is pressed. 9. In the Expression field, following the word scroll, type =+1. Your finished line of code should read: _root.ScrollBox.scroll+=1;. This completes the code needed to scroll the text by an increment of 1.
221
Figure 11-7: You insert the target path to the text box using this dialog box.
10. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. The Expression parameter text box appears. 11. Enter the following code: _root.CompSlider.slideBar._y+=5.5555555 This line of code synchronizes the movement of the white slider bar with the down button when clicked. You may recognize this as an incremental statement. As long as the button is pressed, the white slider bar (a movie clip with the instance name of sliderBar) advances 5.555555 pixels towards the bottom of the slider. The next section explains how the value was determined. 12. Choose ControlTest Movie. Click the down arrow on the slider bar and the text should start scrolling nicely. The Text Field object has several properties that you can use when adding text objects to your designs. For example, if you want to add an End of Page button to a text box, you use the maxscroll property. If you want to add an End of Page button to the project you just finished, the button code looks like Listing 11-3.
To take the design one step further, you can add a Top of Page button. To do so, set the scroll property of the text box equal to 1, which returns the user to the first line of text when the button is clicked.
222
code for the slider bar to consider. An invisible button in the slideBar movie clip is programmed to execute the startDrag action when the button is pressed. The code constrains the movie clips movement from 0 to 100 along the y axis. The slider movement had to be converted into equal increments to scroll the text. After determining the maxscroll property of the text is 18, that result is divided into 100 to return a value of 5.55555. Therefore, the value of the scroll property of the text box is set to the _y property of the slider divided by 5.5555, as shown in Listing 11-4.
When the slider isnt being use to scroll the text, the slider must be set to move in synch with the scrolling text in case the user decides to switch from button scrolling to dragging the slider. Therefore, an expression needs to be set up to increment the slider when an arrow is clicked, as shown in Listing 11-5.
The third line of code shown in the previous listing moves the slideBar by 5.5555 (the result of dividing 100 by the maxscroll value of the text box) when the button is pressed. The next line of code has a conditional statement that prevents the _y property of the slider from exceeding 100. Without this line of code, the slider would continue past the down arrow if the arrow is pressed long enough. The code for the up arrow, shown in Listing 11-6, decrements moves the slider in the opposite direction and prevents it from going above the up arrow.
223
Tip
To determine the maxscroll value of a block of text, select the frame where the text box is displayed in your movie. Make sure it is a keyframe. Open the Actions panel and click ActionsMiscellaneous Actions and then double-click trace. In the Message field, type the name of the dynamic text box variable, followed by a dot ( . ) and the word maxscroll. Click the Expression check box and choose ControlTest Movie. The maxscroll value of the text box is displayed in the Output window. After you determine the maxscroll value, you can delete the trace action.
224
5. In the URL target field, enter the path of the Web site to which you want to hyperlink the text. If the page resides at the same URL, enter the relative path; if the HTML document is at another Web site, enter the absolute path, for example: htttp://www.dasdesigns.net/about.htm. 6. Click the triangle to the right of the target field and choose one of the following: Self: Opens the URL in the same window as the link. Blank: Opens the specified URL in a new browser window. Choose this option and your Flash movie will play in the background. Parent: Loads the URL in the window of the frame that called the link. If the frame isnt nested, the URL opens in the full browser window. Top: Loads the URL in the full browser window, removing all frames. Thats all there is to it. When the movie is published, the users cursor becomes the familiar pointing hand when moved over the text. When the text link is clicked, the linked page opens up in the browser window you specified.
225
6. In the Variable field, enter the same name as the dynamic text box variable the array element will be displayed in. 7. In the Value field, enter the array name and then the element number you want to display. The element number is surrounded with square brackets. Remember the first element of an array is always 0. 8. Click the Expression checkbox. Listing 11-7 shows a variable with a value equal to the third element of an array.
Listing 11-7: Creating a Variable to Display an Array Element in a Dynamic Text Box
tickerText = tickerList[2];
To follow along with this project, copy to your hard drive the scrollTick.fla file from this chapters folder in the CD-ROM that accompanies this book. Use your operating system to disable the files read-only attribute.
To begin the project: 1. Launch Flash and open the scrollTick.fla file. Notice that this project builds on the scrolling text project you completed earlier in this chapter. The elements have been rearranged slightly to accommodate the text box below the banner (see Figure 11-8). The text box is actually nested in a movie clip. If youll remember the discussion about modular ActionScript, you can use this movie clip in any of your designs by choosing FileOpen as Library and dragging an instance of the movie clip into the current document Library.
226
Scrolling ticker
2. Click the text box movie clip and then right-click (Windows) or Ctrl+click (Macintosh) and choose Edit from the context menu. After the movie clip is displayed in symbol-editing mode, notice you have six keyframes on the Actions layer. Select the first keyframe and open the Actions panel to display the code shown here:
// initialize labels and counter k = 0; tickText = ; tickerList = new Array(); tickerList[0] = Welcome to Pepper Cay... your vacation paradise... ; tickerList[1] = White water rafting trips... ; tickerList[2] = Fishing for marlin and kingfish... ; tickerList[3] = Experienced guides available... ; tickerList[4] = Create your own adventure in paradise... ; endLine = tickerList.length;
The code in this keyframe initializes the array and three variables. The variable k is used as a counter, the variable endLine returns the number of elements (length) of the array, which in this case is five. The value of endLine could have been set equal to 5, but that limits you to using this movie clip
227
only with an array with five elements. If you modify this movie clip for use in another design, you can add as many array elements as needed, and the endLine variable will always return the number of elements in the array. The variable tickText is the same variable assigned to the dynamic text box that displays the elements of the array. Another thing to notice is the manner in which the array has been created; each element is created separately. You can accomplish the same thing by creating a variable named tickerList and then entering each array element in quotes and separating them with commas. This particular method was chosen for this project because its easier to see each array elements offset. Youll be referring to each array element by its offset to complete the project. 3. Select the second keyframe. In the Actions panel, you see that a single line of code has been created that initializes a variable named lineNum and sets its value equal to 0. This is the offset of the first element in the tickerList array. This frame has been labeled newLine. 4. Select the third keyframe, which has been labeled lineLoop. In the Actions panel, notice that two lines of code have been created. Two new variables have been declared, as shown below.
len = tickerList[lineNum].length; i = 0;
The variable len returns the length of an individual array element. When the code is first executed, the variable returns the length of the element in the tickerList array at offset 0, the initial value of the variable lineNum. The variable i is another counter. 5. Select the fourth keyframe that has been labeled msgLoop. In the Actions panel, notice a conditional statement has been started for you. Youll be creating the action that executes when the value of k is less than 65. 6. In the Actions panel Script pane, select the first line of code 7. In the left pane of the Actions panel, click ActionsVariables and then double-click set variable. 8. In the Variable field, type tickText 9. In the Value field, type tickText+tickerList[lineNum].charAt (i) Be sure to click the Expression checkbox. This line of code begins displaying text. It takes the initial value of tickText, a null string variable, and sets it equal to itself plus the first character of the first element in the array. The .charAt(i) part of the code returns the string value of character at this position in the string. When the code first executes, it returns the first character (i=0) of the first element (the initial value of lineNum is 0) from the tickerList array. The .charAt element of the code is a Property of the String object.
228
10. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click else. Youll now create the code that executes when the value of k exceeds 65. When k reaches 65, the dynamic text box cannot accept any additional characters. In order for the ticker to display the next character, one character must be removed from the string in tickText. In other words, the number of characters in tickText must be reduced to 64 before the next character can be displayed. To achieve this, you use the substring method of the String object. Youll use this method to return the 1st through 65th characters of the string tickText, which in essence removes the first character. 11. In the left pane of the Actions panel click ActionsVariables, and then doubleclick set variable. 12. In the Variable field, type tickText 13. In the Value field, type tickText.substring(1,65)+tickerList[lineNum].charAt (i) and click the Expression checkbox. This line of code returns a substring of the 1st through 65th characters of tickText and adds the next character to the string. Remember, the first character of a string is position 0. The rest of the code has been written for you. 14. Select the fifth keyframe and open the Actions panel to view the following code.
i = ++i; k = ++k; if (i<len) { gotoAndPlay(msgLoop); }
This line of code increments the value of the variables i and k by a value of 1. The conditional statement evaluates the value of the variable len, which is the length of an array element. As long as the value of i is less than the length of the array element, the movie clip loops to the frame labeled msgLoop and another letter from the array element is added. When the value of i becomes greater than len, frame 6 plays. 15. Select the sixth keyframe and notice the following code in the Actions panel.
lineNum = ++lineNum; if (lineNum==endLine) { gotoAndPlay(newLine); } else { gotoAndPlay(lineLoop); }
The code in this keyframe increments the value of lineNum by 1. When the value of lineNum is equal to endLine, the movie goes to the frame labeled
229
newLine, which sets the value of lineNum equal to 0 and begins displaying the characters from the first array element. Otherwise the movie loops to the frame labeled lineLoop, which sets the value of i equal to 0 to display the first character from the next array element. 16. Click the Back button to exit symbol-editing mode and then choose ControlTest Movie. The movie plays and the text advances one letter at a time across the marquee until the text box is filled, whereupon the next letters advance one at a time. Several things happen in this movie. After the variables are declared and the array is set, the first element in the array is displayed one letter at a time by evaluating the charAt() property of the string data in the array. When the last letter of the string is displayed as determined by the conditional statement, the next element in the array is selected. The conditional statement in frame 4 evaluates the length of the variable stored the string data. When it exceeds the specified value, the substring property of the String object takes the first character away from the string. When the last element in the array is displayed, the code loops back to newLine, which resets to the first element in the array and letters from that element are added to continue the ticker. You can use this movie clip in one of your own designs. All you need to do is change the size of the text box to suit your movie. You can also modify the color, size, and font by selecting the text box and modifying the parameters in the Property inspector. When you change the size of the text box, or any of the text parameters, you have to experiment to get the proper value for k and the ending value of the substring. If you choose a smaller font size, you have to increase the value of k; otherwise, the code will start dropping letters before the end of the text box is reached. Change both values in the fourth keyframe until the text advances properly, as shown in Listing 11-8.
The values you use vary depending upon the font size and size of the text box. Each font has different kerning characteristics, which enters into the value you end up using.
230
On the CD-ROM
Copy the file marqueeComponent.fla to your hard drive. Launch Flash and open the file. In the document Library, youll find a single component. Drag the component on Stage and center it to the top of the document. Open the Property inspector and then click the Parameter tab. Click the magnifying glass to open the Values panel. Three values have already been entered. Click a value and enter your own text. To add additional values, click the button that looks like a plus sign and enter some text. Click OK to apply the modifications and then test the movie. You now have a programmable marquee ticker. The String object has many properties you can use to evaluate string data. In this chapter youve been exposed to the scroll, charAt(), and substring properties. A detailed discussion of each string property is beyond the scope of this book. You are urged to experiment with these properties. To understand what each property does, open the Actions panel, click the Reference icon and then click Objects CoreStringProperties; then click each property for a detailed explanation.
Note
Designer Notes
In this chapter you were introduced to dynamic and input text. You learned how to create a scrolling text box for your designs and how to create a ticker marquee. You were shown how to manipulate string data as well as display string data from an array in a dynamic text box. In the next chapter, youll create some interactive elements for your movies.
12
C H A P T E R
In This Chapter
Building tooltips Creating drag-anddrop elements Creating a user customizable interface Using the Date object Using the Scrollbar component Chapter project: Creating a moving navigation bar
n previous chapters, you learned to create elements such as animated buttons and navigation bars for your designs. In this chapter, the interactivity is cranked up a notch or two. In this chapter, you learn to design interactive interface elements such as tooltips. If youd like to give your viewers the option of dragging interface elements to different areas, youll learn how to create the code to do that in this chapter. Youll also learn how to create the ActionScript where the user can change the color and opacity of a background object by clicking a button and dragging a slider. You can also use ActionScript objects to display the date and time in your designs. In Chapter 11, you learned to create a scrolling text box using buttons of your own design. If time constraints dont allow you the luxury of creating a custom scrolling text box, you can use a Flash UI component to quickly create a scrolling text box. In the chapter project, you learn to create a moving navigation bar.
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
Note
Building Tooltips
If you add enough bells and whistles to your designs, it may be difficult for some viewers to ascertain exactly what each element of your design does. You can alleviate some of the confusion by creating tooltips that appear when the users
232
roll their mouse over certain elements in your designs. For example, you can add a tooltip that tells the viewer what theyll see when a button is clicked, as shown in Figure 12-1.
Figure 12-1: You can create a tooltip that displays information to the viewer.
233
7. Click the Back button to exit symbol-editing mode. 8. Delete the symbol instance. The master symbol is stored in the document Library. Youll duplicate it to create the other tooltips needed for your design. 9. Choose WindowLibrary. The document Library opens. 10. Duplicate the basic tooltip symbol as needed to create the additional tooltips for your design. When you duplicate each symbol, give it a name that reflects the tooltips function. After you create the duplicates, edit them to change the text. Remember, you can edit a symbol from the document Library by doubleclicking its name. After you create the tooltips, youre ready to add them to your design. When the movie loads, you dont want the tooltips to be visible so you place them off Stage. Then you create the necessary code to make the tooltip appear when the users mouse hovers over a button.
Figure 12-2: You can specify the registration point for the tooltip.
To position the tooltips, follow these steps: 1. Choose WindowLibrary. The document Library opens.
234
2. Select all the tooltips. To select all of them, select the first tooltip, and then click the additional tooltips while holding down the Shift key. 3. Drag the tooltips to a position off Stage. 4. Click the arrow to the left of the word Properties. The Property inspector opens. 5. Record the values in the X: and Y: fields. Youll need these values when you create the ActionScript to return the tooltips after the users mouse rolls off the button. 6. Choose ModifyDistribute to Layers. A new layer is created for each tooltip. The layer is labeled with the tooltips name, as shown in Figure 12-3. By creating a separate layer for each tooltip, you can select each tooltip, even though they are in identical positions.
Tip
If youre creating a design that involves many objects, create a layer folder to store the tooltips in. After you create the tooltips, you can close the folder and it takes up only one position on the timeline. The tooltips in Figure 12-3 are stored in a folder.
7. Select a tooltip and then open the Property inspector. To select an individual tooltip, lock and hide the other tooltip layers. Then youll be able to select the tooltip by clicking it (see Figure 12-4). 8. Enter a name for the tooltip in the <Instance Name> field. 9. Repeat Steps 7 and 8 to name the other tooltips in your design.
Figure 12-3: You distribute each tooltip to its own layer so you can work with them individually.
235
Tooltip instance
Instance name
Figure 12-4: Lock and hide the tooltip layers so you can edit an individual tooltip.
After youve named all of the tooltips, youre ready to create the ActionScript that makes the tooltips appear. You could create the same script for each object that uses a tooltip. However, that can get rather tedious if you have several tooltips. The easier solution is to create one function to display the tooltips and another to hide them.
236
To create the tooltip functions: 1. Select the top timeline layer and insert a layer. Label the layer Actions.
Tip
Its a good idea to get in the habit of creating a separate layer for actions you assign to keyframes on the timeline. All of your timeline ActionScript will be on one layer, making it easier for you to edit and debug the ActionScript.
2. Select the first frame on the Actions layer and then click the arrow to the left of the word Actions. 3. In the left pane of the Actions panel, click ActionsUser-Defined Functions and then double-click function. 4. In the Name field, enter a name for the function. 5. In the Parameters field, type mc This designates that the function is applied to movie clips. 6. Click ActionsMiscellaneous Actions and then double-click evaluate. The Expression field appears above the Script pane. 7. In the Expression field, type _root[mc]._x=_xmouse This line of code sets the _x property of the movie clip called by the function equal to the current _x position of the mouse. 8. Click ActionsMiscellaneous Actions and then double-click evaluate. 9. In the Expression field, type root[mc]._y=_ymouse The function you just created displays the tooltip. Now you need to create a function to hide the tooltip. To create a function to hide the tooltips, follow these steps: 1. Select the last line of code (the solitary curly brace) you just created. 2. In the left pane of the Actions panel, click ActionsUser-Defined Functions and then double-click function. 3. In the Name field, enter a name for the function. 4. In the Parameters field, type mc 5. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. The Expression field appears above the Script pane. 6. In the Expression field, type _root[mc]._x= followed by the value you recorded from the Property inspector when you added the tooltips to your design. 7. Repeat Steps 5 and 6 to create an expression for the _y property of the movie clip. Listing 12-1 shows two functions that show and hide tooltips.
237
Notice that a value of 5 was added to the _xmouse and _ymouse properties in the code shown in Listing 12-1. This was to allow a bit of space so the item the users mouse hovers over is still visible. After you create the functions, you create the code that displays or hides the movie clips depending on where the users mouse is in relation to the button.
If you want a tooltip to appear when a users mouse is over a graphic, you must nest the graphic in a movie clip with an invisible button.
To program the buttons: 1. Select a button and open the Actions panel. 2. In the left pane of the Actions panel, click ActionsUser-Defined Functions and then double-click call function. Three parameter text boxes appear above the Script pane. 3. In the Object field, type _root This tells the Flash Player that the function will be applied to an object on the root timeline. 4. In the Method field, type the name of the function you created to display the tooltip. 5. In the Parameters field, type the instance name of the tooltip you want to appear. The instance name must be surrounded by quotation marks, as shown in Listing 12-2.
238
6. Click the first line of code and in the parameter text area, click the Roll Over checkbox, making sure you deselect the checkbox for the default Release event. The button is now programmed to call the tooltip when a users mouse rolls over the button target area. 7. Click the last line of code (the curly brace) and repeat Steps 2 through 6 to call the function that hides the tooltip. For the event, choose Roll Out. Listing 12-2 shows a typical ActionScript to call and put a tooltip.
On the CD-ROM
To see an example of tooltips at work, copy to your hard drive the toolTips.fla file youll find in this chapters folder on the CD-ROM that accompanies this book. Disable the files read-only attributes and then open the file in Flash. Choose ControlTest Movie to publish the file and display it in another window. Roll your mouse over the buttons to display the tooltips. After you finish testing the movie, close the window. If you want to examine the ActionScript, open the Actions panel and then select the individual buttons. If adding tooltips is cumbersome for your design, you can create a movie clip with a Help document and position it off Stage. Create a Help button that, when clicked, changes the position of the Help document so that it appears within the movie. Create a Close Window button that when clicked moves the document out of view.
Tip
239
240
If you create target windows for loading movie clips, you can use the startDrag action to give the viewer the capability of dragging the window after the movie clip loads. If your target window is a movie clip with a blank first frame, add the invisible button to the second frame of the movie clip.
Closing a window
You can give viewers of your movies the option to close a window by creating a small movie clip with the letter X inside an unfilled rectangle. Nest an invisible button in the movie clip and then program the button to close the window. The method you use to program the button depends on how the window was created. If the window is the second frame of a target movie clip that another movie is loaded into, program the button to unload the movie and go to the first frame of the target movie clip, which is blank. Listing 12-4 shows typical ActionScript for closing a target movie clip window and unloading a movie from the target.
You can also close a window by changing its _visible property to false. The code for a button that hides a window from view is shown in Listing 12-5.
On the CD-ROM
To view a document with a few drag-and-drop elements, copy to your hard drive the dragNdrop.fla file found in this chapters folder on the CD-ROM that accompanies this book. Use your operating system to disable the files read-only attribute. Launch Flash, open the file and choose ControlTest Movie. You can drag-and-drop the windows and the menu. The menu is a derivate of the flyout menu you created in Chapter 10. Click Menu to expand the menu. Both windows can be closed by clicking the X. After youre finished testing the movie, close the window and open the Actions panel to examine the various scripts used in the movie.
241
To learn how you can create a background that the user can change, copy to your hard drive the interface.fla file found in this chapters folder on the CD-ROM the accompanies this book. Disable the files read-only attribute using your operating system utilities.
To create a user-customizable interface: 1. Launch Flash and open the interface.fla file. 2. Choose ControlTest Movie. The document is published and appears in a new window. 3. Click the Control Panel label. The control panel slides into the interface. The panel motion was created by using a motion tween. 4. Drag the slider bar. The opacity of the background movie clip changes, as shown in Figure 12-5. The slider used to change the opacity is constrained to a motion between 0 and 100 along the x axis. The _alpha property of the background image is set equal to the _X property of the slider. When the slider is all the way to the right, its _x property is 100 and the background is opaque; when the slider is at 0, the background movie clip is transparent.
Note
The color swatches are not functional yet. Youll be programming them to change the color of the background when they are clicked. But instead of creating a long ActionScript for each button, youre going to create a function named setBGcolor that is called when each button is clicked.
5. Close the window to return the movie-editing mode. The buttons are nested within a movie clip. You can edit items nested in a movie clip by double-clicking the movie clip and then double-clicking individual items nested in the movie clip. Every time you double-click, you open a nested symbol and make it available for editing.
242
Figure 12-5: The control panel is programmed to change the color characteristics of the background image.
To program the buttons: 1. Double-click the control panel on the left side of the Stage. You are now in symbol-editing mode and the workspace title bar reads Control Panel, the name of the symbol. 2. Click the arrow to the left of the word Properties. The Property inspector opens. Notice that the symbol has already been given an instance name of open panel. This is part of the path to the buttons. 3. Double-click the panel again. The title bar should now read Inner Panel. 4. Click the color swatch in the upper-right corner of the lower panel, directly below the word color. If you still have the Property inspector open, the description should read instance of #FF6699. When the buttons were created, they were named after their hexadecimal value. 5. Click the arrow to the left of the word Actions. The panel title bar should read Actions-Button. 6. In the left pane of the Actions panel, click ActionsVariable and then doubleclick set variable. 7. In the Variable field, type chip Youll use the contents of this variable to change the color of the background when the button is clicked. 8. In the Value field, type 0xFF6699 That nomenclature may look familiar. This is the same formatting used to change an objects color characteristics using the Color object.
243
9. Click the Expression checkbox. When you create code like this for your own designs, youll already know the name of the function; therefore, you can create the code to call the function while coding the button. As mentioned in the previous section, the name of the function youll be creating is called setBGcolor. The instance name of the background movie clip youll be applying the function to has been labeled bg. 10. In the left pane of the Actions panel, click ActionsUser-Defined Functions and then double-click call function. 11. In the Object field, type _root 12. In the Method field, type setBGcolor 13. In the Parameters field, type bg. Your finished code for the button should look exactly like Listing 12-6.
14. Click the Scene 1 button to the right of the Back button to return to movieediting mode. The other buttons have already been programmed. In order to make the buttons active, you need to create a function that uses the setRGB method of the Color object to apply the transformation. To create the function: 1. Click the first frame on the Actions layer. 2. Click the arrow to the left of the word Actions. 3. In the left pane of the Actions panel, click ActionsUser Defined Functions and then double-click function. 4. In the Name field, type setBGcolor 5. In the Parameters field, type mc This signifies the function is to be used on a movie clip. 6. In the left pane of the Actions panel, click ActionsVariables and then doubleclick set variable.
244
7. In the Variable field, type myColorObject 8. Place your cursor in the Value field and then in the left pane of the Actions panel, click ObjectsMovieColor and then double-click newColor. The object is added to the script and your cursor blinks between two parentheses. 9. Type mc and click the Expression checkbox. 10. In the left pane of the Actions panel, click ObjectsMovieColorMethods and then double-click setRGB. 11. In the Object field, type myColorObject and then place your cursor inside the Parameters field. When you worked with the color object in Chapter 9, you specified a hexadecimal value in this field. However, youre using the function with more than one color value. The value changes whenever one of the color buttons in the control panel is clicked. You set the variable of the variable chip equal to the hexadecimal value of the buttons color using the proper formatting for the Color object. You use the value of the variable in the parameters field by specifying the path to the variable and the name of the variable. 12. Click the Insert a Target Path button to open the Insert Target Path dialog box. Click the Absolute mode radio button if its not already selected. 13. Click the plus sign (+) to the left of the fullPanel button and then click openPanel, as shown in Figure 12-6. This is the target path to the button where you set the value of the variable chip. 14. In the Value field, place your cursor to the right of the target path that was entered when you clicked the button and type .chip The code for your finished function should look exactly like Listing 12-7.
245
The other buttons are already programmed. The value of the variable chip is set equal to the hexadecimal value of the buttons color, formatted for the setRGB method of the color object. To test your code choose ControlTest Movie. After the movie opens in another window, click the control panel button to open the panel. Click each color button and watch the color of the background movie clip change. Drag the slider to vary the look of the background even further by changing the value of background movie clips _alpha property.
246
Listing 12-8: Retrieving the Current Date Using Methods of the Date Object
mydate = new Date(); day = mydate.getDay(); month = mydate.getMonth(); currentdate = mydate.getDate(); year = mydate.getFullYear();
The code in Listing 12-8 returns the date. To display the date in a dynamic text box with a variable name of current date, youd create the script in Listing 12-9.
247
The two arrays contain the days and months as string objects. The first element of an array is 0. The getDay and getMonth methods of the Date object returns Sunday and January as a 0. The last lines of code combine the elements to display the date in a dynamic text box with the variable name of current_date. The first element of the current_date variable, myday[day] gets the current day for the week from the myday array. The mymonth[month] element of the variable gets the current month from the mymonth array. You retrieve an element from an array by specifying its offset surrounded by square brackets. The variable day and month return a number that retrieves the proper element from each array.
On the CD-ROM
In this chapters folder on the CD-ROM that accompanies this book is a file named currentDate.fla. Copy the file to your hard drive and use your operating system utilities to disable the files read-only attributes. Open the file in Flash for an example of a movie clip that displays the current date. Choose ControlTest Movie to see the date displayed. To use the movie clip in your own design, open the file using the Open as Library command and then drag the movie clip into the current document Library. You can then edit the movie clip to change the attributes in the dynamic text box to display a different font or different font color.
248
After creating an instance of the Date object, you create a variable for each method you want to retrieve. Listing 12-10 shows a script that creates an instance of the Date object and three variables to store the information.
Listing 12-10: Retrieving the Current Time from the Host Computer
mydate = new Date(); hours = mydate.getHours(); minutes = mydate.getMinutes(); seconds = mydate.getSeconds();
To display the date in a dynamic text box, you have to convert the 24-hour clock to a 12-hour clock, unless of course your client is a military organization. Listing 12-11 shows a script that displays the time correctly in a dynamic text box.
249
Notice that the code in the previous example specifies the enterFrame clip event. This code is in a movie clip. Choosing the enterFrame clip event continually updates the time as the host computers clock ticks away. The lines of code below the seconds variable set the display time to AM or PM and modify the output to a 12-hour clock. These are all conditional statements. If the variable hours returns a value less than 1, its midnight and the variables value is reset to 12 midnight on a 12-hour clock. If the value of hours exceeds 12, the value is reduced by 12 to display the proper time on a 12-hour clock; for example, 1300 hours is 1:00 PM on a 12-hour clock. The last two variables add the string 0 to seconds or minutes if they are less than 10. The current_time variable combines all the variables with the necessary punctuation to properly display the time in a dynamic text box.
On the CD-ROM
In this chapters folder on the CD-ROM that accompanies this book is a file named currentTime.fla. Copy the file to your hard drive and use your operating system utilities to disable the files read-only attributes. Open the file in Flash for an example of a movie clip that displays the current time. Choose ControlTest Movie to see the date displayed. To use the movie clip in your own design, open the file using the Open as Library command and then drag the movie clip into the document Library of your current project. You can then edit the dynamic text box in the movie clip to change the text attributes and choose a different font style or color. If you choose a larger font size, you may have to resize the dynamic text box with the Text tool.
250
7. Click the triangle to the right of the Line Type field and choose Multiline from the drop-down menu. 8. Select the dynamic text box with the Arrow tool and then right-click (Windows) or Ctrl+click (Macintosh) and choose Scrollable from the context menu. 9. Double-click the text box to return to text-editing mode. 10. Enter the desired text in the box or paste the contents of a document youve copied from a word processing program. Make sure you enter enough text to exceed the boundary of the text box. 11. Choose WindowComponents. The Components panel opens. 12. Drag an instance of the ScrollBar component and drop it inside the text box. The component resizes itself to the height of the text box (see Figure 12-7). When the movie is published, the scrollbar becomes functional.
ScrollBar parameters ScrollBar component
Figure 12-7: You can use the ScrollBar component to quickly create a scrolling text box.
251
To learn how to create a moving navigation bar, copy to your hard drive the movingNavBar.fla file youll find in this chapters folder on the CD-ROM that accompanies this book. Disable the files read-only attributes using your operating system utilities.
To create the moving navigation bar: 1. Launch Flash and open the movingNavBar.fla file. The project is partially completed. You have a basic interface and a navigation bar, as shown in Figure 12-8.
252
2. Select all the buttons and then choose InsertConvert to Symbol. The Convert to Symbol dialog box appears. 3. Name the symbol, choose the movie clip behavior, and click the center left square in the Registration section (see Figure 12-9).
Figure 12-9: You convert the navigation bar to a movie clip symbol.
4. Click OK. The buttons are converted to a movie clip symbol and the symbol is added to the document Library. 5. Select the symbol you just created and then choose EditEdit Selected. You are now working in symbol-editing mode. 6. Select all the buttons and then choose EditCopy. The buttons are copied to the clipboard. 7. Choose EditPaste in Place. You now have a carbon copy of the buttons in the navigation bar. Your next task is to align the first button so that it appears after the last button on the navigation bar you copied. The document you are working with is 600 pixels wide, as is the navigation bar. To move the selected buttons, you change the x value in the Property inspector.
253
8. Click the arrow to the left of the word Properties to open the Property inspector. 9. In the X field, type 600 The buttons are perfectly aligned. 10. Click the Back button to exit symbol-editing mode. When you return to movie editing mode, the symbol is still selected. 11. Click the triangle to the left of the word Actions. The Actions panel opens. 12. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click if. 13. In the Condition field, type this 14. In the left pane of the Actions panel, click ObjectsMovieMovie ClipMethods and then double-click hitTest. Your cursor flashes between a pair of parentheses. 15. Type the following: _root._xmouse, _root._ymouse,true The condition you just created tests to see if the mouse has hit the navigation bar. 16. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. 17. In the Expression field, type this._x-=0 You may recognize this as a decremental expression. If the mouse hits the navigation bar, the x position of the navigation bar decrements by a value of 0. In other words, there is no motion. To set the navigation bar in motion, you need to use the else action. 18. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click else. 19. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. 20. In the Expression field, type this._x-=5 This expression decrements the x position of the navigation bar by a value of five pixels. But if the navigation bar continues to move, eventually it will scroll past the end of the movie. To prevent this, you create another conditional statement using the if action. The navigation bar is 600 pixels long, and you tacked a 600 pixel duplicate to the back end. The first button on the navigation bar is at x coordinate 0. When the navigation bar moves 600 pixels to the left, the navigation bar you copied to the back end is fully displayed. Therefore, you set the _x property of the navigation bar to 0 as soon as it exceeds 600. This is how the navigation bar appears to be continuous.
254
21. In the left pane of the Actions panel, click ActionsConditions/Loops and then double-click if. 22. In the Condition field, type this._x<=-600 23. In the left pane of the Actions panel, click ActionsMiscellaneous Actions and then double-click evaluate. 24. In the Expression field, type this._x=0 As soon the movie clips _x property is less than or equal to 600, the property is reset to 0 and the navigation bar appears as though it is never-ending. 25. Select the first line of code that reads onClipEvent (load) {. 26. In the parameter text area, select the Enter Frame clip event. Your code for the navigation bar should look like Listing 12-12.
27. Choose ControlTest Movie. After the movie publishes, it displays in another window. If you followed the steps exactly, the navigation bar should begin moving to the left. Move your mouse over the navigation bar and it stops. This technique can also be used when the navigation bar exceeds the width of the movie. For example, if you create a document that is 600 pixels wide, and you have eight buttons that are 100 pixels long, you change the values accordingly. When you duplicate the buttons and paste them onto the back end of the original navigation bar, you change the value in the X field of the Property inspector to 800.When the navigation bars _x property is less than or equal to 800, you reset the property value to 0.
255
Tip
For another interesting variation, you can create a vertical navigation bar and have it continuously scroll from top to bottom by decrementing the navigation bars _y property.
Designer Notes
In this chapter, you learned to create interactive elements for your interfaces. You learned how to create tooltips as well as how to create an interface that the user can modify. You learned to use the Date object to display the time and date in your designs. The chapter project showed you how to create a navigation menu that moves from left to right and appears to have no end. In the next chapter, you learn to use the Sound object to modify the characteristics of sounds in your Flash designs.
13
C H A P T E R
In This Chapter
Creating a soundtrack Looping a soundtrack Using streaming sound Creating a Sound object Using methods of the Sound object Chapter project: Creating a sound controller
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
Creating a Soundtrack
There are two ways you can work a soundtrack into your designs. First, you can import the sound file into the document Library and add it to the timeline. When you use
258
a soundtrack in this manner, the soundtrack must load at runtime before the first frame of the movie plays. If you have a relatively small sound file, this is generally not a problem. However, a better solution for adding sound to your Flash production is to publish the soundtrack in a separate movie and then give the viewer the option to load the soundtrack or not. When you choose this option, your base movie loads more quickly because you dont have the overhead of the sound file to load in addition to your other content. Whichever method you choose, you must first import the sound into the document.
Importing a sound
When you decide to use a soundtrack in one of your designs, you can import any of the following file types: WAV (Windows only) AIFF (Macintosh only) MP3 (Windows and Macintosh) If you have QuickTime 4 installed on your machine, you can also import the following sound format types: AIFF (Windows or Macintosh) Sound Designer II (Macintosh only) Sound only QuickTime Movies (Windows and Macintosh) Sun AU (Windows or Macintosh) System 7 Sounds (Macintosh only) WAV (Windows or Macintosh) The format you import depends on the source material you have available. If you use sound sampling software to create your own loops, you can choose a format to render the file with. The AIFF and WAV formats create a good quality soundtrack at the expense of a large file size. If you choose the MP3 format, you can choose a compression setting to apply to the file. However, you can also apply MP3 compression to a sound file within Flash. When you apply MP3 compression using Flash export settings, you can choose a Bit Rate as high as 160 kbps. This setting gives you CD-quality sound, but it also generates the largest file size. Unless you need a Bit Rate setting higher than 160, it is recommended that you render a file in the native format for your operating system (WAV for Windows and AIFF for Macintosh) and apply MP3 compression within Flash.
259
To import a sound file into a Flash document: 1. Choose FileImport. The Import dialog box opens. 2. Locate the sound file you want to import and then click Open. The dialog box closes and the sound is stored in the document Library. After you import a sound into Flash, you can then add it anywhere on the timeline. To add a sound to the timeline, you use the Property inspector. To add a sound to the timeline, do the following: 1. Select the keyframe where you want the sound to begin playing. 2. Click the arrow to the left of the word Properties. The Property inspector opens. 3. Click the triangle to the right of the Sound field. A menu appears with a list of all sounds stored in the document Library. 4. Select a sound from the menu. 5. Click the triangle to the right of the Effect field and choose one of the following: None: The default setting applies no effect to the sound. Left Channel: Plays sound in left channel only. Right Channel: Plays sound in right channel only. You can use this effect in conjunction with the Left Channel effect applied to a different sound on a different timeline to play different sounds in each speaker. Fade Left to Right: Fades sound from left speaker to the right. Fade Right to Left: Fades sound from right speaker to the left. Fade In: Gradually increases the amplitude of the sound to full volume during the duration of the sound. Fade Out: Gradually decreases the amplitude of the sound to silence during the duration of the sound. Custom: Lets you create your own effect by modifying the sounds characteristics. When you choose this option, a dialog box appears. Creating a custom effect will be covered in the next section. 6. Click the triangle to the right of the Sync field and choose one of the following options: Event: An event sound is synched to the keyframe where you add the sound. The sound plays in its entirety, regardless of the length of the timeline and regardless of whether the movie is still playing. Choose Event when you are creating a background sound loop. Event sounds are mixed when the movie is published.
260
When you use the Event Sync option for a button sound, the sound starts when the button is clicked and plays for its duration. If the button is clicked again before the sound finishes playing, a second instance of the sound plays simultaneously. Start: Works the same as Event. However, if the sound is already playing, a new instance of the sound does not start. This setting is recommended for a button sound. Stop: Stops a sound.
Tip
If you create an introduction with sound for one of your designs, add a keyframe to the last frame of your introduction, open the Property inspector, and from the Sound field menu, choose your intro soundtrack and from the Sync field menu choose Stop. Open the Actions panel and create the code to go to and play the first frame of the main movie. Create a skip intro button and program the button to go to and play the last frame of the introduction. When the user clicks the button, the last frame of the introduction plays, stops the introduction sound, and transports the viewer to the first frame of the main scene of your design.
Stream: Streams the sound into the viewers browser. The Flash Player forces the animation to synchronize with the streaming sound, dropping frames if necessary to keep up. If the data cant download into the users browser quickly enough, the sound will stop. If you do not have enough frames on the timeline, the sound will stop when the last frame is reached. Streaming sound is best used to synchronize a narration with a movie. Streaming sound is not recommended for background music as popping sounds and other artifacts may occur when Flash breaks the sound into packets for streaming. 7. In the Loop field, enter the number of times you want the sound to loop for. When youre using a sound for background music, enter a high value so the sound plays continuously while the movie is being viewed. However, when you create background music that loops continuously, provide some way for the viewer to stop the sound. Either create a button and assign the stopAllSounds action to it or create a sound controller with volume control and an Off switch (as you will do in this chapters project). After you complete the previous steps, the sound is added to the timeline. If you have enough frames on the timeline, the sounds waveform is displayed, as shown in Figure 13-1. Otherwise, you see a truncated waveform, but if you choose Event or Start for the Sync method, the sound will still play in its entirety
261
Sound waveform
Event menu
Selected sound
Figure 13-1: You can insert a sound at any point on the timeline.
To create a custom effect: 1. Import a sound and add it to the timeline as discussed previously, or select a sound on the timeline you want to edit. 2. Click the arrow to the left of the word Properties. The Property inspector opens. If the sound is already on the timeline, the sounds name is displayed in the Sound field. Otherwise, follow the previous steps to set up the imported sound on the timeline. 3. Click the triangle to the right of the Effect field and choose Custom. Alternately, you can click the Edit button. The Edit Envelope dialog box opens (see Figure 13-2), and you can perform any of the following tasks: To shorten the duration of the sound, drag the Time In and/or Time Out controls. With these controls, you change the duration of the sound and also the point where the sound begins or stops.
262
To edit the sound, click anywhere inside one of the windows to create a handle. You have two windows, one for each channel. When you create a new handle, one appears in each window. You can drag each handle independently to apply different settings to each channel and create custom fade in or fade out effects. Drag a handle down to decrease the amplitude (volume) of the sound. To zoom in on the sound waveform, click the magnifying glass with a plus sign (+) in it. To zoom out and view more of the waveform, click the magnifying glass with a minus sign () in it. To toggle the unit of measure between seconds and frames, click the Seconds and Frames buttons. To preview the sound, click the Play button. To stop the sound, click the Stop button. 4. Click Done to apply the edits to the selected sound.
Tip
Select one of the preset effects as a starting point for a custom effect. Click the Edit button and then follow the previous steps to modify the effect to suit your design.
Seconds Frames
Stop
Play
263
264
This setting determines the amount of time Flash spends analyzing the sound as it is compressed. When you choose Best, Flash takes longer to analyze the sound while compressing it, resulting in a higher quality sound. If you have a slower machine and you are changing the settings on a large sound file, it will take longer to publish the movie or test the sound when you choose Best. If you have the time, choose Best for the highest sound quality. 7. To preview the sound with the new settings, click Test. Flash applies the current compression settings to the sound and plays it. If the sound quality is acceptable, click OK to apply the settings; otherwise, select a different Bit Rate. Your objective is to get the smallest possible file size with acceptable sound quality. Of course, what is acceptable will be largely dependent on the client you are creating the site for. For example, if youre applying compression settings to sound files for a musicians Web site, youll end up using a higher Bit Rate to showcase the subtle nuances of the music and best showcase the musicians talent.
Note
If you are compressing a sound for a multimedia application that plays from a CD-ROM, you can choose a higher Bit Rate as file size is not as important when you play a Flash movie from CD-ROM.
Figure 13-3: You can use MP3 compression when high quality music and a small file size are required.
265
To use the Speech compression option: 1. Choose WindowLibrary. The document Library opens. 2. Double-click the sound you want to compress with the Speech option. The Sound Properties dialog box appears. 3. Click the triangle to the right of the Compression field and choose Speech from the drop-down menu. 4. Click the triangle to the right of the Sample Rate field and choose one of the following: 5 khz is the lowest sample rate acceptable for human speech. This setting results in the smallest file size at the expense of quality. 11 khz is the best compromise between sound quality and file size. 22 khz is the setting to choose if there is background music with the spoken narrative. 44 khz is recommended if the narrative includes background music and is to be included in a CD-ROM multimedia application. When you choose a setting, the file size of the sound is displayed at the bottom of the dialog box, as shown in Figure 13-4. 5. Click the Test button to preview the sound. If the sound quality is acceptable, click OK to apply the new settings to the sound and close the dialog box. Otherwise, select a different sample rate and retest the sound.
Figure 13-4: You can choose the Speech compression option for sound files with narration.
266
267
268
269
To create the linkage for ActionScript: 1. Choose WindowLibrary. The document Library opens. 2. Select a sound and then right-click (Windows) or Ctrl-click (Macintosh) and choose Linkage from the context menu. Alternately, choose Linkage from the Library options menu. Either method opens the Linkage Properties dialog box. 3. Click the Export for ActionScript check box (shown in Figure 13-5). 4. Enter a name in the text field. By default Flash uses the filename of the sound. You can choose to use the filename as an ActionScript identifier or enter a name such as sound1. Dont use any spaces when you create the name. If you must separate two words in a name, either capitalize the first letter of the second word or separate the words with an underscore. 5. Click OK to apply the linkage and close the dialog box. After you create ActionScript linkage for a sound in the document Library, you can attach the sound to an instance of the Sound object.
Figure 13-5: You create ActionScript linkage to modify a sound in the document Library.
Attaching a sound
You can attach a sound from the document Library that has ActionScript linkage to an instance of the Sound object. You can also attach an instance of the Sound object to a .SWF movie that you have loaded into the base movie. When you attach a sound, you refer to it by its linkage nomenclature or by the level that you load the sound into. You can attach the sound to a movie clip, a button, or to a keyframe on the timeline. To attach a sound to an instance of the Sound object: 1. Select the object or keyframe where you want to create ActionScript to attach a sound. 2. Click the arrow to the left of the word Actions. The Actions panel opens.
270
3. Click ObjectsMovieSoundMethods and then double-click attachSound. Two parameter text boxes open above the Script pane. 4. In the Object field, enter the name of the Sound object instance you created. 5. In the Parameters field, enter either the linkage identifier of a sound from the document Library or the level into which you loaded a soundtrack movie. If you enter an ActionScript identifier, place quotation marks around the name. Listing 13-1 shows the ActionScript to attach a sound from the document Library to a Sound object; Listing 13-2 shows the ActionScript to attach a sound loaded into level 99 to an instance of the Sound object.
After you attach a sound to your instance of the Sound object, you can use the various methods of the Sound object to manipulate the sound. If you load a soundtrack movie into a movie, it begins playing as soon as the keyframe or object in which you created the ActionScript to load the movie with loads. If youre affording your viewers the option of whether or not to listen to the soundtrack, you create a button that, when clicked, loads the soundtrack. However, if you attach a sound from the document Library, it wont begin playing until you invoke the Start method of the Sound object.
Starting a sound
You can start an attached sound from the document Library by using the start method of the Sound object when a keyframe is reached, a movie clip loads, or a button is clicked. When you use the start method, you can specify at which point in the duration of a sound it begins playing and you can specify the number of times the sound plays. After a sound starts, it plays in its entirety, even if ActionScript is executed to attach and play a different sound from the document Library.
271
To start a sound: 1. Select the object or keyframe that you want to trigger the sound. 2. Choose ObjectsMovieSoundMethods and then double-click start. Two parameter text boxes appear above the Script pane. 3. In the Object field, enter the name of the Sound object you want to begin playing. 4. In the Parameters field, enter the parameters for the sound offset and number of loops. If you want the sound to play only once, you dont need to enter anything in the Parameters field. However, you can change the point at which the sound begins playing and the number of times the sound plays by entering values in the Parameters field. Below the field you see the message (secondsOffset, loops). This is the proper syntax for offsetting the start of the sound and specifying the number of loops. If you just want to loop the sound, enter 0 for the seconds offset followed by a comma and a value for the number of times you want the sound to play. If you want to offset the starting point of the sound, enter a value in the field followed by a comma and the number of times you want the sound to loop. Listing 13-3 shows ActionScript for a sound that starts playing the sound three seconds into its duration and loops the sound 16 times. Note that when you offset the start of a sound, the offset is applied to each loop.
Stopping a sound
You use the stop method of the Sound object to stop playing the sound currently attached to the instance of the Sound object. This method is useful if you have several sounds in a document Library that are programmed to play when a button is clicked. If viewers click another button before the previous sound has finished playing, Flash mixes the sounds, which is an undesirable occurrence if the sound being playing is background music or is linked to another action such as the frames of a movie clip the sound is attached to. In order to prevent this, you create ActionScript for each button using the stop method to cease playing the currently attached sound.
Note
If you program several buttons to load different movie soundtracks, as long as all of the movie soundtracks are loaded into the same level, clicking a button will stop the current soundtrack from playing when the new soundtrack is loaded. To stop all sounds from playing, create a button and then create the ActionScript to unload the soundtrack movie from the level soundtracks are loaded into.
272
To stop a sound from playing: 1. Select the object or keyframe that will cause the sound to stop. 2. Click ObjectsMovieSoundMethods and then double-click stop. The Object parameter text box appears above the script pane. 3. Enter the name you assigned to the instance of the Sound object. Listing 13-4 shows ActionScript to stop a Sound object named mysound from playing.
In addition to starting and stopping a sound, you can use methods of the Sound object to control the volume of the sound, pan the sound from one speaker to the other, and cause another action to execute when the sound stops playing.
273
Note
It is possible to play a sound at a higher amplitude (volume) than original by specifying a value greater than 100. To a limited extent, you can do this to compensate for a sound with low volume. However, when you exceed the original amplitude of a sound by a large percentage, distortion occurs.
Panning a sound
Another useful sound method is the setPan method. You use the setPan method to vary the balance of a sound between speakers. By default, a sound is distributed evenly between the left and right speakers. You can use the setPan method and enter a value between 0 and 100 to pan the sound towards the right speaker; a value between 0 and 100 pans the sound to the left speaker. To pan a sound: 1. Select the object or keyframe that will cause the balance of the sound to change. 2. Choose ObjectsMovieSoundMethods and then double-click setPan. The Object and Parameters text fields appear above the Script pane. 3. In the object field, enter the name of the Sound object you are modifying. 4. In the Parameters field, enter a value. Listing 13-6 shows ActionScript that when executed pans the sound towards the left speaker.
274
object to trigger another action when the sound finishes. For example, if you create a scene that displays images while a background narration plays, you can use the onSoundComplete event to play the next scene immediately after the sound finishes playing. To trigger an event when a sound finishes playing: 1. Select the object or keyframe that will cause the onSoundComplete event to be invoked. For example, you can create ActionScript on a keyframe to start playing a sound at the beginning of a scene. You can add the onSoundComplete event on this frame to start playing the next scene when the sound stops. 2. Choose ObjectsMovieSoundsEvents and then double-click onSoundComplete. Three parameter text boxes appear: Object, Method, and Parameters. The method field is already filled in with onSoundComplete. 3. In the Object field, enter the name of the Sound object. 4. In the Parameters field, you can enter the name of a user-defined function that you want the Flash Player to execute when the sound finishes playing. Alternately, you can select another action you want executed when the sound stops, such as the goto action. Listing 13-7 shows ActionScript that plays a frame labeled Slide1 in the History scene when the sound stops.
Copy to your hard drive the Soundcontroller folder from this chapters folder on the CD-ROM that accompanies this book. Use your operating system to disable each files read-only attribute.
275
To begin the project: 1. Launch Flash and open the soundbegin.fla file. 2. Choose InsertNew Symbol. The Insert New Symbol dialog box opens. 3. Choose the Movie Clip behavior, name the symbol soundController, and click OK to enter symbol-editing mode. 4. Select the first frame and then click the arrow to the left of the word Actions. The Actions panel opens. 5. Click ActionsVariables and then double-click set variable. Two parameter text boxes appear above the Script pane. 6. In the Variable field, type mysound 7. Click inside the Value field, and in the left pane of the Actions panel, click ObjectsMovieSound and then double-click newSound. After creating an instance of the Sound object, you need to attach a sound to it. In this case, youll use a button to load a soundtrack movie and also create the ActionScript to attach the sound. After you create an instance of the Sound object, you add the buttons to load additional soundtracks and sliders to control the sound to the movie clip.
276
This code gives the button drag-and-drop capability. The buttons motion is constrained to 100 pixels on the x axis, which is perfect for creating a sound controller. 4. Click the soundController title above the workspace. 5. Click the arrow to the left of the word Properties. The Property inspector opens. 6. Type volControl in the <Instance Name> field. 7. Click the slider movie clip, and while holding down the Alt key (Windows) or Options key (Macintosh), drag the symbol to create a new instance of it. 8. In the Property inspector, type 0 in the X field and 25 in the Y field. 9. In the <Instance Name> field, type panControl 10. Choose WindowLibrary. 11. Drag an instance of the soundButton symbol on Stage and align it to the left of the two sliders. 12. Click the Arrow to the left of the work Actions. The Actions panel opens. 13. Choose ActionsBrowser/Network and then double-click loadMovie. 14. In the URL field, type sound1.swf, accept the default Level option, and in the Text field, type 99. This code loads the soundtrack movie into level99. 15. Choose ObjectsMovieSoundMethods and then double-click attachSound. Two parameter text boxes appear above the Script pane.
277
16. In the Object field, type mysound and in the Parameters field, type _level99. Your code should look exactly like Listing 13-9. 17. Click the button labeled Sound to select it, and then press the Alt key (Windows) or Option key (Macintosh) to create another instance of the button. 18. With the button still selected, click the arrow to the left of the word Actions and modify the buttons script by changing the second line of code to loadMovieNum(sound2.swf, 99). There are two more soundtracks in the project folder. If you feel ambitious, create two more instances of the button and change the code so that the buttons load sound3.swf and sound4.swf respectively. 19. Click the Back button to exit symbol-editing mode.
Now that the movie clip components are programmed, its time to put the symbol to work. To do this you drag an instance of the soundController symbol on Stage, create the initial states for each slider, and then use methods of the Sound object to manipulate the sounds when the sliders are dragged.
278
The Actions panel opens. 4. Choose ActionsMiscellaneous Actions and then double-click evalutate. The Expression parameter text box appears above the Script pane. 5. With your cursor inside the Expression field, click the Insert a Target Path button. The Insert Target Path dialog box opens. 6. Click the Relative mode radio button, click the plus sign (+) to the left of panControl button, and then click knob (see Figure 13-6). 7. Click OK to add the target path and close the dialog box. 8. In the Expression field, type the following text after the target path: ._x=50 This code sets the _x position of the pan slider to 50, the halfway point of the scale, which is a perfect balance between the two speakers. 9. Repeat Steps 5 through 8 but insert the target path to the volControl knob and set the _x property to 75. Accept the default load clip event. Your code should look like Listing 13-10.
279
The initial value for each slider sets the volume and balance when viewers click a button to load a sound. After setting the initial values for the sliders, you have to create the code that sets the volume and balance of the Sound object as the sliders are dragged. To constantly evaluate the position of each slider as the movie plays, you use the enterFrame clip event. To create the code that evaluates the position of the sliders: 1. Click the arrow to the left of the word Actions. The Actions panel opens. 2. Select the last line of code (the solitary curly brace). 3. Choose ObjectsMovieSoundMethods and then double-click setVolume. The Object and Parameters fields appear above the Script pane. 4. In the Object field, type mysound 5. Click inside the Parameters field and type volControl.knob._x You may recognize this as the target path to the volume control slider knob. This time instead of setting the value of the slider knobs _x property, the code evaluates and returns the value of the property. When the slider is dragged, the value of the knobs _x property changes and sets the volume of the sound. 6. Choose ObjectsMovieSoundMethods and then double-click setPan. 7. In the Object field, type mysound 8. In the Parameters field, type 100-(panControl.knob._x*2) To perfectly balance the sound between the speakers, the parameter of the setPan method must be 0. The initial position of the slider is 50. The expression in the Parameters field equates the position of the slider to a value that can be used by the setPan method. When the slider is dragged all the way to the right, the _x property of the slider is 50. The equation bumps it up to 100, the value needed to pan the sound to the right speaker. Using this equation makes it possible to use the same slider to set the volume and pan of the sound. 9. Click the line of code that contains the second clip event and change the clip event to enterFrame. Your finished code for the movie clip should look like Listing 13-11.
280
10. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. The slider knobs move to their initial positions. 11. Click either of the sound buttons to begin playing a soundtrack. 12. Drag the volume slider to vary the volume and then drag the pan slider to change the balance between speakers. After youre done experimenting with the sliders, close the window to return to movie-editing mode. 13. Add any needed labels to identify the sliders and sound buttons and then select all the objects on Stage that comprise the sound controller.
Tip
As a finishing touch, you can add a button to stop the sound. When you program this button, use the unloadMovie action and in the Parameter text box, specify the level youve loaded the soundtrack into.
14. Choose InsertConvert to Symbol. The Convert to Symbol dialog box opens. 15. Choose the Movie Clip behavior, name the symbol Sound Controls, and then click OK.
After you convert the movie clip to a symbol, it becomes modular and you can use it in any movie. To use it in another movie, choose FileOpen as Library. Drag an instance of the Sound Controls movie clip into the current document Library and you can use it in your design. When you publish the movie and upload it to a Web site, upload files named sound1.swf and sound2.swf. Now the soundtracks will play when the buttons are clicked and viewers can control the volume and balance by dragging the sliders. Figure 13-7 shows the controller at work in a published Flash movie.
281
Figure 13-7: Using a sound controller to modify sound in a published Flash movie.
Designer Notes
In this chapter, you learned to work with sound in Flash. You learned to create a soundtrack within the movie and modify sounds by creating a custom effect. Also presented was creating a soundtrack movie and creating the necessary ActionScript to load the soundtrack on demand. You were also shown how to use methods of the Sound object to modify sounds in the document Library or modify soundtracks loaded into the movie. The chapter project showed you how to create a working sound controller. In the next chapter youll learn to use the Flash MX diagnostic tools to debug faulty ActionScript.
Debugging an ActionScript
hen you add ActionScript to a design, your take your production to the next level. The ability to add interactivity to a design with ActionScript is what gets you the big jobs from high-paying clients. At the same time, adding interactivity to a design can also increase the level of difficulty for you as a designer. ActionScript by its very nature is created on different keyframes, within different objects, and assigned to different buttons. When something goes awry with a complex ActionScript design, you cant just look at a written script and figure out the error is on line such and such. True, the error will be in one or more specific lines of code, but on which frame is the faulty code; in which movie clip? There are so many places to look, tracking down faulty code can be a time-consuming process. Fortunately you have two indispensable tools you can use to debug a movie: the Debugger and the Movie Explorer. You can also add elements to your ActionScript to trace variables. You can also stop a movie at selected places to see what is happening when a line of code executes, or if there is an error in your ActionScript, doesnt execute. In this chapter youll learn to use the Debugger to trace your ActionScript designs as well as add actions to your scripts that enable you to keep track of whats happening as the movie plays.
Note
14
C H A P T E R
In This Chapter
Using the Debugger Using the trace action Tracking ActionScript with comments Tracing a variable Using the Movie Explorer
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
284
Figure 14-1: You can test the movie within the authoring environment.
Notice the graph across the top of the workspace in Figure 14-1. This is the Bandwidth Profiler. (Youll use the Bandwidth Profiler in Chapter 15 when you create an animated preloader.) Across the top of the workspace, you see a timeline. As the movie plays, the small arrow moves from frame to frame. If the multi-frame movie stops due to faulty ActionScript, you know exactly which frame the problem occurs on by viewing this timeline. If your design is a single-frame production and your ActionScript is embedded in movie clips, your task of tracking down the faulty script isnt quite as easy.
285
You can also preview your design in a Web browser. When you use a Web browser to preview your productions, you see exactly what the end user sees. If you use ActionScript to achieve visual effects, you should preview your production in a Web browser as well as in the authoring environment. To preview your design in a Web browser, choose FilePublish PreviewHTML. After choosing this command, the movie is published and plays in your systems default Web browser, as shown in Figure 14-2.
Figure 14-2: When you preview your design in a Web browser, you see exactly what your audience will see.
If you notice an error when testing the movie, youll probably have a pretty good idea what part of your code went awry. But sometimes it can get a bit trickier, especially when you have arrays and variables scattered throughout your movie. The easiest way to track a problem with variables is by using the Debugger.
286
To launch the Debugger, choose ControlDebug Movie. After choosing the command, the movie is published and displays in another window. The movie is halted on the first frame and the Debugger is displayed (see Figure 14-3).
Variables
Figure 14-3: You can use the Debugger to trace elements in your movie.
To begin debugging the movie, click the Continue button. In Figure 14-3, the Continue button has already been clicked. Notice that in the left window of the upper window, there are several icons similar to the ones you see in the Insert Target Path dialog box. These icons represent all the objects in your design that can have ActionScript assigned to them. If you dont assign an instance name to a movie clip, a default name is assigned to it; for example, _level0.instance1. Named instances are referred to by the level they reside in followed by their label. Now you can see how important labeling movie clips is. To find out something about a movie clip, click its icon. After selecting a named instance, you can find out what the properties of the instance are by clicking the Properties tab. You can trace variables by clicking the Variable tab. If a movie clip has local variables, you can trace their values by clicking the Locals tab. You can also target one or more variable and trace their values by clicking the Watch tab.
Watching a variable
You can trace the value of several variables and watch their values change as the movie plays. This is the course of action to take if you suspect the problem with your ActionScript is due to a variable.
287
To watch a variable: 1. In the left pane of the Debugger, click any named instance icon you know contains the variable you want to watch. 2. Click the Variables tab. 3. Select the variable you want to watch. 4. Right-click (Windows) or Ctrl+click (Macintosh) and choose Watch from the context menu. 5. Select any additional variable you want to watch and repeat Step 4. 6. Click the Watch tab to watch the values change as the movie plays. If youre not sure which objects or which variables are in your movie, you can view a list of them while youre debugging the movie.
Figure 14-4: You can display a list of movie objects while debugging your design.
After you view the objects in your movie, you may remember a variable value that should be displayed in the variables window but isnt.
288
Figure 14-5: You can display a list of all the variables in your movie.
After viewing a list of variables and watching the Debugger, you may decide you need to trace a variables value at one or more points in the movie.
Tip
You can print a hard copy of the variables in your movie by right-clicking (Windows) or Ctrl+clicking (Macintosh) inside the Output window and then choosing Print from the context menu.
289
is never displayed when you test or debug the movie, you know the frame is not playing and the ActionScript you created to play the frame is in error. When you use the trace action, the results of the trace are displayed in the Output window. To keep track of a variable or object with the trace action: 1. Select the keyframe or object you want to trace. 2. Open the Actions panel and choose ActionsMiscellaneous Actions and then double-click trace. The Message field appears above the Script pane. 3. Enter the message you want displayed when this point in the movie occurs. To trace the value of a variable at this juncture in the movie, enter the variables name and click the Expression checkbox. 4. Repeat Steps 1 through 3 for any additional objects you want to trace. After you trace one or more objects, the message or value of the variable is displayed in the Output window when you test or debug the movie. If you trace several objects, you may not know which value relates to a particular variable. In order to know what variable value is displaying, you can combine a text message with the value of the variable by enclosing the message in quotes, typing a plus sign (+) and then the name of the variable. Figure 14-6 shows the ActionScript for displaying a message in the Output window along with the variables value.
Figure 14-6: You can combine a message with the value of a variable.
When you trace several objects in a movie, the message in the Output window updates quickly, sometimes so quickly you cant read the message as it scrolls past. When you trace several objects, you can momentarily stop the movie by setting breakpoints.
290
Setting a breakpoint
When you set a breakpoint in the Actions panel, the breakpoint is stored with the saved *.FLA file. When you set a breakpoint in the Debugger, it is in effect only for the current debugging session. When you close the window and return to movieediting mode, the breakpoints you set in the Debugger are lost. To set a breakpoint in the Actions panel: 1. Select the object or keyframe that contains the code where you want to set a breakpoint. 2. Open the Actions panel and select the line of code where you want the movie to pause. 3. Click the Viewing options icon and choose View Line Numbers. When you set breakpoints and line numbers are visible, a red dot appears alongside all line numbers where breakpoints are set. 4. Click the Debugger Options icon that looks like a stethoscope and choose Set Breakpoint from the menu. 5. Continue adding breakpoints as needed. After you set breakpoints and add trace actions, youre ready to flush out the source of your bug.
291
To debug a movie with breakpoints: 1. Choose ControlDebug Movie. The movie is published and opens in another window. The Debugger appears and is paused on the first frame of the movie. 2. Click the Continue button. The movie begins playing and halts at the first breakpoint, as shown in Figure 14-7. After the movie pauses at a breakpoint, a yellow arrow appears to the left of the breakpoint line number. While the movie is paused at a breakpoint, you can exercise different options by clicking one of the buttons shown in Figure 14-7. The buttons and their functions are: Continue: Restarts the movie and stops it at the next breakpoint. Stop Debugging: Resumes the movie but does not stop the movie at breakpoints. Step Over: Advances the movie to the next line of code after the breakpoint. Step In: If the line of code where the breakpoint is set calls a function, clicking this button displays the first line of code in the function. Click the button again to advance to the next line of code in the function. Step Out: Steps out of the function and restarts the movie.
Note
When youre in a debugging session, you modify breakpoints from within the Debugger, as the next section discusses.
292
Remove All Breakpoints Toggle Breakpoint Stop Debugging Continue Step Over Step In Step Out
To remove a single breakpoint: 1. Select the keyframe or object that contains the code where the breakpoint is set. 2. Open the Actions panel. 3. Select the line of code with the breakpoint. A red dot is displayed to the left of each line number where you set a breakpoint. If breakpoints are not visible, choose the View Line Numbers option from the View Options menu. 4. Click the Debugger Options button and choose Remove Breakpoint. To remove all breakpoints from a document, open the Actions panel, click the Debugger Options button that looks like a stethoscope, and choose Remove All Breakpoints.
293
A comment is a note you can add to describe what a line of ActionScript does. Comments are useful when debugging a movie. They are also useful when you modify the movie after a period of time and may not remember exactly what a line of code is meant to accomplish. You add comments to a script in the Actions panel. To add a comment to your ActionScript: 1. Select the object or keyframe that contains the code you want to add a comment to. 2. Open the Actions panel. 3. Select the line of code prior to where you want the comment to appear. 4. Choose ActionsMiscellaneous Actions and then double-click comment. The Comment field appears above the Script pane. 5. Enter any descriptive text and close the Actions panel. When you see a comment in the Actions panel or Debugger, it is preceded by two forward slashes (//). The default syntax color for a comment is light gray.
294
Show ActionScripts Show Buttons, Movie Clips, and Graphics Show Text Show Videos, Sounds, and Bitmaps Show Frames and Layers
Designer Notes
In this chapter you learned to use the Debugger to track down faulty ActionScript. You also learned to trace variables and add comments to your ActionScript to clarify what a line of code is designed to do. You were shown how to add breakpoints within your ActionScript to pause the movie so you could compare what is happening when a line of code is reached. You also learned to use the Movie Explorer to track down items and code in your documents. In the next chapter, you learn to create ActionScript objects for your movies.
IV
In This Part
Chapter 15 Building Web Site Elements with ActionScript Chapter 16 Creating Flash Eye Candy Chapter 17 Integrating Flash with HTML
15
C H A P T E R
In This Chapter
Creating a Flash form Creating an animated preloader Creating a printable frame Chapter project: Creating an e-commerce catalog
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
298
Figure 15-1: You create a preloader to keep the viewer entertained while the main movie loads.
299
300
Figure 15-2: You use the Bandwidth Profiler to analyze your movie.
Figure 15-3: If you prefer, you can view the Bandwidth Profiler as a streaming graph.
301
You can modify the bandwidth setting by choosing Debug and then choosing one of the menu settings (14.4K, 28.8K, or 56K), or you can choose one of the User Settings. You can modify a user setting to suit a specific bandwidth (such as a users intranet) by doing the following: 1. Choose DebugCustomize to open the Custom Modem Settings dialog box shown in Figure 15-4. 2. Decide which menu setting you are going to modify, and in the Menu Text field, select the current menu text and enter your own description for the custom setting. 3. Inside the Bit Rate field, enter a bandwidth setting. If you are modifying a setting for a clients intranet, contact the clients system administrator for the proper value. 4. Click OK to close the dialog box. The custom setting is added as a menu command.
Custom setting
Figure 15-4: You can create a custom modem setting to suit a particular need.
After you select a bandwidth setting, a red line appears at the bottom of the Bandwidth Profiler. If any frame appears above the red line, it contains more information than the selected modem setting can download and may cause the movie to pause while additional data streams into the users browser. Click the frame to select it, and the amount of data contained in the frame is displayed in the State section in the Bandwidth Profilers left pane. After you identify one or more frames as a potential bottleneck, you can test the movie in streaming mode as your viewers will see it.
302
mode, you can compare the progress of the streaming data to the current frame playing. By comparing the streaming data to the progress of the movie, youll know whether or not you need to create a preloader. To view the movie in streaming mode: 1. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. 2. Choose ViewBandwidth Profiler. 3. Choose Debug and then choose a modem connection setting. Choose the setting that comes closest to the connection speed your viewers will access the Internet with. Its always best to err on the lower side of the scale and choose the next lowest setting. 4. Choose ViewShow Streaming. Flash starts playing the movie again, only this time it loads at the selected connection speed. As the movie loads, a green bar appears at the top of the timeline indicating the amount of data that has been loaded. Flash begins playing the movie when enough data has streamed to play the first few frames. As the movie starts playing, a playhead in the form of a small inverted triangle begins moving across the timeline. This indicates the current frame being played. If the playhead catches up with the green bar and stops, this indicates that Flash does not have enough data to play the frame. The Flash Player plays the next frame when it has received enough additional data. 5. If the playhead stops before the movie loads completely, record the number of the frame the movie stops on. When the movie begins playing again, watch the playheads progress in reference to the streaming indicator bar. If it stops again, record the position. If not, the previous frame where the playhead stopped is the source of the bottleneck. After you determine which frame is causing your movie to halt, your next task is to create a preloader that plays until enough data has loaded to play the movie without interruption.
303
The best preloader is one thats short, sweet, and to the point. Follow the steps below to create a preloader with a small bar that gets larger as the movie loads, giving the viewer a visual representation of the download progress. To create a preloader: 1. Choose WindowScene. The Scene panel opens. 2. Click the Add Scene button that looks like a plus sign (+). 3. Name the scene Preloader, drag it to the top of the hierarchy, and then close the Scene panel. 4. Choose InsertNew Symbol. The New Symbol dialog box appears. 5. Choose the Graphic behavior, name the symbol bezel, and click OK to enter symbol-editing mode. 6. Create a wide and short rectangle with a stroke and no fill. This will be the outline for your preload progress bar. 7. After you create the symbol, click the Back button to exit symbol-editing mode. 8. Create a new symbol, only this time choose the Movie Clip behavior, name the symbol preloadBar, and click OK to enter symbol-editing mode. 9. Create a rectangle with a fill and no stroke the same width and height as the bezel symbol you just created. Choose a color that is harmonious to your design. Align the rectangle so that its left edge is at the registration point. You can do this by selecting the rectangle, opening the Property inspector, and then entering a value in the X field that is half the rectangles width. 10. After you create the rectangle, click the Back button to exit symbol-editing mode. 11. Select the first frame of your preloader and drag an instance of the preloadBar movie clip on Stage. Use the Align panel to center it to Stage. 12. Create a second layer and drag an instance of the bezel symbol on Stage. Use the Align panel to center it to the Stage. 13. Select the preloadBar movie clip and click the arrow to the left of the word Properties. The Property inspector opens. 14. Type bar in the <Instance Name> field and close the Property inspector. After you create the symbols for your preload bar and align them to Stage, you create the ActionScript that loops the animation while the movie data loads. To animate the preloadBar symbol, you change its _xscale to 0, rendering the movie clip invisible. Youll create an expression that increases the _xscale property of the preloadBar movie clip as more data loads. Then youll create the actual loop that
304
plays the preload animation. In one frame of the loop, youll create a conditional statement that evaluates how many frames have loaded. When the number of frames loaded is greater than the frame that caused the movie to stop playing when you tested the movie, the preload loop stops and the first frame of the movie plays. To create the ActionScript for the preload loop: 1. Create a new layer and label it Actions. 2. Select the first frame of the Actions layer, and then click the arrow to the left of the word Actions. 3. Choose ActionsVariables and then double-click set variable. 4. In the Variable field enter siteLoaded and in the Value field enter 0. 5. Choose ActionsVariable and then double-click set variable. 6. In the Variable field, type _root.bar._xscale and in the Value field, type siteLoaded This sets the initial size of the preloadBar movie clip to 0 pixels wide. 7. Select the second frame on the Actions layer and then press F6 to convert it to a keyframe. 8. Click the arrow to the left of the word Actions to open the Actions panel. 9. Choose ActionsVariables and then double-click set variable. 10. In the Variable field, type siteLoaded 11. Place your cursor in the Value field and type (_root 12. In the left pane of the Actions panel, choose ObjectsMovieMovie ClipMethods and then double-click getBytesLoaded. This method of the Movie Clip object measures the number of bytes that have loaded. The fact that youve specified the _root timeline instructs the Flash Player to measure the number of bytes that have loaded. 13. Place your cursor to the right of the parentheses in the value field and type _root 14. In the left pane of the Actions panel, choose ObjectsMovieMovie Clip Methods and then double-click getBytesTotal. This method of the Movie Clip object measures the total number of bytes in the movie. 15. Place your cursor to the right of the word Total and type the following: )*100 Dividing the bytes loaded by the total bytes gives you a value that when multiplied by 100 gives you a value you can use to increase the _xscale of the preloadBar, which gives the viewer a visual representation of the loading progress. Your finished code for the second frame of the preloader should look like Listing 15-1.
305
To complete the preloader, you need to create two more keyframes: a conditional statement and ActionScript to recycle the preload loop if the conditional statement evaluates as false. To finish creating the preload loop: 1. Select the ninth frame and convert it to a keyframe by pressing F6. 2. Click the arrow to the left of the word Actions to open the Actions panel. 3. Choose ActionsConditions/Loops and then double-click if. The Condition parameter text box appears above the Script pane. 4. In the left pane of the Actions panel, click Properties and then double-click framesLoaded. 5. Enter > followed by the frame number you determined caused the movie to pause plus 10. (You add 10 to compensate for the number of frames in the preload loop.) For example, if the frame number is 30, you would enter >40. 6. In the left pane of the Actions panel, choose ActionsMovie Control and then double-click goto. After you add the goto action to your script, the actions parameters appear above the Script pane. Youll have to specify the frame number and the scene to go to when the proper frame has loaded. 7. In the Scene parameter text box, choose Next Scene, or if youve named the main scene, choose the scene name from the drop-down menu. Choose 1 for the frame number. Listing 15-2 shows the code for a conditional statement that breaks the preload loop after the seventeenth frame has loaded. 8. Select the tenth frame and convert it to a keyframe by pressing F6. 9. In the left pane of the Actions panel, choose ActionsMovie Control and double-click goto. 10. Type 2 in the Frame field. 11. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. 12. After the movie begins playing, choose ViewShow Streaming. Flash begins playing the movie again, streaming the data with the current connection setting. The preload bar slowly advances as the data loads. When the bar is fully extended, the first frame of the main movie begins playing.
306
Thats the basic formula for creating a preloader. You can make the preloader more interesting by creating a simple animation where the message Loading, Please Wait appears letter by letter. You can also create an expression similar to the one used to increase the scale of the preload bar to display the number of bytes in the movie and the total number of bytes loaded. You display the results of this expression in a dynamic text box with the same variable name you use to create the expression. In order to give the viewer a whole number to look at, use the round method of the Math object. Listing 15-3 shows the code required to create a preloader that displays the number of bytes loaded. Notice the string expression KB Loaded thats added to the result.
CGI is being used for this example. The process is similar for a server that uses ASP, PHP, or ColdFusion. Check with the support personnel of the server hosting the site where your Flash form will be displayed for specific instructions.
307
user inputs information into the text box, Flash stores the data until the user clicks the Submit button. Figure 15-5 shows input text box parameters being modified in the Property inspector.
Figure 15-5: You create the form elements using the text tool.
CrossReference
Remember that when you create input text boxes, you can specify the type of information that will be accepted by the variable. You can also limit the number of characters that will be stored by the variable. For more information on creating input text boxes, refer to Chapter 11.
Figure 15-6 shows a finished Flash form complete with a Submit and Reset button.
Figure 15-6: You can use input text boxes and other elements to create an aesthetically pleasing form for your designs.
308
309
The code may look a little daunting. When you analyze a script like this, youre looking for the information that is required to forward the information to a recipient. When you create a variable, you need to enter a value and a name for the variable. If you analyze the script, you notice several instances where the script asks for a value. With each value is also a name. This is the information you need to create the ActionScript to submit the form results to the intended recipient. The script in Listing 15-5 requires values for four items: sendto, server, subject, and resulturl. When you create the ActionScript for the Submit button, you create a variable for each required item in the CGI script and set the variable value equal to the value in the script. To code a Submit button for the above CGI script, follow these steps: 1. Select the button that will submit the information. 2. Click the arrow to the left of the word Actions to open the Actions panel. 3. Choose ActionsVariables and then double-click set variable. Two parameter text boxes appear above the Script pane. 4. In the Variable field, enter the first name from the CGI mail forwarding script. If you are coding a Submit button for the example in Listing 15-5, type sendto This is the recipient. All mail forwarding scripts require a recipient. 5. In the Value field, enter the value for the name. Following the scenario for Listing 15-5, you would enter [email protected] 6. Repeat Steps 3 through 5 for the other required names in the CGI script. 7. Click ActionsBrowser Network and then double-click getURL. Three parameter text boxes appear above the Script pane. 8. In the URL field, enter the path to the Web hosting services CGI bin. For example: http://scripts.digitalchainsaw.com/cgi-bin/mailto.exe
310
9. Click the triangle to the right of the Variables field and choose Send Using GET. This instructs the Flash Player to get the data from the variables in the movie and send them to the specified URL. After the document is published as a Flash movie and you upload it to the Internet, when a user fills out the form and clicks the Submit button, the information is forwarded to the specified recipient. Listing 15-6 shows the ActionScript for the example in Listing 15-5.
311
To create a printable frame: 1. Choose InsertNew Symbol. The Create New Symbol dialog box appears. 2. Name the symbol and choose the Movie Clip behavior. 3. Select the first frame and either import the artwork you want to give viewers the capability of printing or open the document Library and drag an instance of it into the movie clip. 4. Add a print button to the frame. You can use a button from one of the Common Libraries or create one of your own. 5. Select the keyframe and then click the arrow to the left of the word Properties. The Property inspector opens. 6. Type #p in the <Frame Label> field. This syntax tells the Flash Player that the frame is printable. If you create the ActionScript to print the frame as is, Flash prints everything, including the button. To restrict printing to a given area, follow the next steps. 7. Select the next frame in the movie and convert it to a keyframe by pressing F6. 8. Open the Property inspector and in the <Frame Label> field, type b# This nomenclature tells Flash that the contents of the frame act as a bounding box, restricting the print area. 9. Click the Onion Skin button near the bottom of the timeline. By enabling Onion Skins, you can see the content of the printable frame. 10. Select the Rectangle tool and create a rectangle with no fill that surrounds the area you want to give viewers the capability of printing. 11. Click the printable frame and then click the arrow to the left of the word Actions to open the Actions panel. If you dont add the stop action to the printable frame, the movie clip will advance to the second frame and all viewers see is the bounding box you created in Step 10. 12. Choose ActionsMovie Control and then double-click stop. 13. Select the button and in the left pane of the Actions panel, choose ActionsPrinting and then double-click Print. Thats all you need to do to create a printable frame. When the movie is published and the button is clicked, the frame prints on the viewers default printer.
312
To follow along with this exercise, copy the eCommerce.fla file to your hard drive from this chapters folder on the CD-ROM that accompanies this book. Use your operating system utilities to disable the files read-only attributes.
To create an e-commerce catalog: 1. Launch Flash and open the eCommerce.fla file. You already have several buttons set up on the Stage and a target window. The movie clips for each product are already in the document Library. Youll create ActionScript linkage for the Hat movie clip. 2. Choose WindowLibrary. The document Library opens. 3. Right-click (Windows) or Ctrl+click (Macintosh) the movie clip symbol named Hat and then choose Linkage from the context menu. The Linkage Properties dialog box opens. 4. Click Export for ActionScript. Flash automatically assigns the name Hat as an ActionScript identifier, as shown in Figure 15-7. 5. Click OK to close the dialog box and assign the identifier to the movie clip. 6. Click the button on Stage with the hat icon and then double-click the arrow to the left of the word Actions to open the Actions panel. 7. Choose ObjectsMovieMovie ClipMethods and then double-click attachMovie. Two parameter text boxes appear above the Script pane. 8. Place your cursor in the Object field and then click the Insert A Target Path button. The Insert Target Path dialog box appears. Make sure youre in Absolute mode.
313
9. Click the button labeled Product. This is the instance name of the target window on the right side of the movie that was already labeled for your convenience. 10. Click OK to add the target path to the script and close the dialog box. Now that youve assigned the target path, you need to fill in the parameters. The attachMovie method has four parameters, three of which youll be using to attach the Hat movie clip to the target window. The first parameter is the linkage identifier, the second parameter is the new name of the attached movie clip, and the third parameter is the depth. The depth is the level you attach the movie clip to. The base movie is _level0. Youll be attaching the movie clip to _level1, so the depth is 1 as well. 11. In the Parameters field, type Hat,Product,1 Make sure to place quotation marks around the linkage identifier and the new name. 12. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. 13. Click any of the buttons to display a different product in the target window.
Figure 15-7: You can create ActionScript linkage for a movie clip.
By using the same methods presented in this exercise, you can create a one-frame movie and display many different products. If youre using other ActionScript to modify the object, when you attach each movie clip, use the same New Name for each movie clip to simplify the task of creating other code. If your client has an extensive product catalog, break the catalog into categories and create a separate movie for each catalog. Create a product category menu using one of the techniques presented earlier in this book and then use the loadMovie action to load a category movie on demand.
Designer Notes
You covered quite a bit of ground in this chapter. You learned to analyze a finished design to make sure it loads quickly into a users browser. Expanding on this knowledge, you learned to create a preloader to prevent a movie from halting
314
before enough data streamed to the users browser. You learned to create elements for a Flash form and create the ActionScript to forward the results to a recipient via a CGI forwarding script. Also covered was creating ActionScript to print out a frame. By completing the chapter project, you learned how to use the attachMovie method of the Movie Clip object to load a movie clip from the document Library into a target window. In the next chapter, youll learn to use ActionScript to create appealing eye candy for your designs.
16
C H A P T E R
In This Chapter
Using the Mouse object Creating a mouse chaser Creating a dynamic background Creating a mask with ActionScript Creating a custom cursor Creating motion trails Creating a starburst backdrop Chapter project: Creating a Flash slide show
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
316
chaser. The mouse chaser youll be creating is a movie clip nested in a movie clip. The nested movie clip uses the duplicateMovieClip action and the setProperty action to create random clones of a star shape. Youll be programming the parent movie clip to follow the mouse.
On the CD-ROM
To follow along with this exercise, copy to your hard drive the mouseChaserBegin.fla that youll find in this chapters folder on the CD-ROM that accompanies this book. Use your operating system utilities to disable the files read-only attributes.
To create a mouse chaser: 1. Launch Flash and open the mouseChaserBegin.fla file. In the center of the scene, you see one solitary movie clip. 2. Double-click the movie clip. Flash enters symbol-editing mode and the dark_star movie clip is available for editing. This is the movie clip that creates the clones of the star. The ActionScript has already been written for you. Before you program the main movie clip, examine the ActionScript for this movie clip. 3. Click the arrow to the left of the word Actions. The Actions panel opens and the code shown in Listing 16-1 is displayed.
The actions for this movie clip are executed every time the frame is entered; therefore, the code is continually creating ten copies of the original star. The second line of code creates a for loop with ten iterations. The next line of code duplicates the original movie clip, giving it a new name of chase appended by the current iteration of the loop. The third through fifth lines of code set the _x, _y, and _alpha (opacity)properties of the duplicate movie clips. The target part of the setProperty action uses the eval action to evaluate each duplicate as it is created. The value of each property is generated using the random method of the Math object. When the movie clip chases the mouse, youll see a field of twinkling stars lagging slightly behind the mouse.
317
To finish creating the ActionScript for the mouse chaser: 1. Click the Back button to exit symbol-editing mode. 2. Select the movie clip and then click the arrow to the left of the word Actions to open the Actions panel. 3. Choose ActionsVariables and then double-click set variable. Two parameter text boxes appear above the Script pane. 4. In the Variable field, type diff_x 5. In the Value field, type _x-_root._xmouse and click the Expression checkbox. This line of code figures the distance between the current _x position of the mouse chaser and the current _x position of the mouse. 6. Repeat Steps 3 through 5 to create a variable named diff_y and set its value equal to _y_root._ymouse. This line of code records the distance between the _y position of the mouse chaser and the _y position of the mouse. Again, make sure to click the Expression checkbox. 7. In the left pane of the Actions panel, choose ActionsMiscellaneous Actions and then double-click evaluate. 8. In the Expression field, type _x=_root._xmouse+(diff_x/2) This line of code sets the _x position of the mouse chaser equal to the x position of the mouse plus the variable diff_x divided by 2. In a nutshell, this line of code creates a slight lag behind the mouse. The faster the mouse is moved, the larger the value of diff_x. The variable is divided by 2 so the mouse chaser doesnt lag too far behind when the mouse is moved rapidly. 9. Repeat Steps 7 and 8 to create a new expression that reads _y=_root._ymouse+(diff_y/2) This expression sets the _y position of the mouse chaser, again creating a lag between the mouse chaser clip and the mouse. 10. Select the first line of code that reads onClipEvent (load) { and in the parameter text area, click the Mouse move radio button. When you choose the Mouse move clip event, the code will be executed when viewers move their mouse across the scene. 11. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. Drag your mouse around the screen and watch the sparkling field of stars follow it, similar to what is shown in Figure 16-1.
318
Figure 16-1: A mouse chaser is entertaining eye candy for any design.
To follow along with this exercise, copy to your hard drive the simpleChaserBegin.fla file. Use your operating systems utility to disable the files read-only attribute.
To create an ActionScript mouse chaser: 1. Launch Flash and open the simpleChaserBegin.fla file. All you have to work with is a solitary movie clip, which is designated by the white registration point in the center of the Stage.
319
2. Click the movie clip to select it and then click the arrow to the left of the word Actions. The Actions panel opens. Notice that a considerable amount of ActionScript has already been created for you. The code (shown in Listing 16-2) generates a random color for the mouse chaser.
Before creating the empty movie clip, take a moment or two to examine the ActionScript in Listing 16-1. You can modify this script to suit other movies where you need to generate a random color. When the movie clip initially loads, a new array is created. The elements of the array are the same numbers and letters that are used to designate the hexadecimal format of a color. The code to generate the color appears after the enterFrame clip event. The first order of business is a new array called colorArray. Notice there are no elements specified for the array. This is an associative array. It will be storing the data generated by the next few lines of code. The for loop runs for six iterations, which is the exact number of characters used to designate a hexadecimal color. Each iteration of the loop generates a random number between 0 and 15. Remember that the first element of an array is always 0. The next line of code starts filling the colorArray. Each element of the colorArray is set equal to the [k] (the random number between 1 and 15 generated by the last line of code) element number of the HexDec array. Finally, a variable called rndColor is created by plucking the elements from the colorArray. Now that you know how to create ActionScript to generate a random color, its time to create the empty movie clip.
320
To create the empty movie clip: 1. Select the last line of code that reads rndColor =
0x+colorArray[0]+colorArray[1]+colorArray[2]+colorArray[3]+c olorArray[4]+colorArray[5];.
2. In the left pane of the Actions panel, choose ObjectsMovieMovie ClipMethods and then double-click createEmptyMovieClip. Two parameter text boxes appear: Object and Parameters. 3. In the Object field, type _root The empty movie clip will reside on the root timeline. 4. In the Parameters field, type line, 1 The first parameter (line) is the ActionScript identifier for the empty movie clip. ActionScript identifiers are always specified with quotation marks. The second parameter is the depth, or level, that the object will be displayed on. In this case, the line will be displayed on _level1. Remember this code follows an enterFrame clip event. Therefore, the code is evaluated every time the Flash Player enters the frame. 5. In the left pane of the Actions panel, choose ActionsVariables and then double-click with. 6. In the Object field, type _root.line 7. In the left pane of the Actions panel, choose ObjectsMovieMovie Clip Drawing Methods and then double-click lineStyle. Two parameter text boxes appear above the Script pane: Object and Parameter. 8. In the Object field, type _root.line This is the path to the empty movie clip. In the Parameters field, youll be specifying the actual style of the line. The lineStyle has three parameters: thickness, RGB value, and alpha. The ActionScript has already been generated to create a random color value. Youll also be creating code to generate a random thickness and alpha properties. 9. Place your cursor inside the Parameter field and type Math.random()*6, rndColor, Math.random()*100 The completed code does three things: The first section generates a random value between 0 and 6, which creates a line thickness between 0 (hairline thickness) and 6 pixels. The second part of the code plugs in the value of the random color to designate the rgb (color) parameter.
321
The third part of the code generates a random value for the lines _alpha property, which varies the opacity of the line. When the line bends towards the cursor, the opacity of the line varies between transparent and solid depending on the value generated by the random method of the Math object. 10. In the left pane of the Actions panel, choose ObjectsMovieMovie ClipDrawing Methods and then double-click moveTo. The moveTo Drawing method specifies the starting point for the object being drawn. You can enter specific x and y coordinates. In this case, youll be entering code to generate a random position. 11. In the Object field, type _root.line 12. In the Parameters field, type Math.random()*500, Math.random()*100 This code generates a random starting point for the line within an area of 500 pixels by 100 pixels from the center of the empty movie clip. 13. In the left pane of the Actions panel, click ObjectsMovieMovie ClipDrawing Methods and then double-click curveTo. This Drawing method curves a line to a designated point. In this case, you want the line to curve to the mouse from a randomly generated point in the movie. 14. In the Object field, type _root.line 15. In the Parameters field, type Math.random()*500,Math.random()*100, _xmouse, _ymouse This line of code curves the line from a random point within the specified coordinates directly to the mouses x and y coordinates. 16. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. As you move your mouse around the Stage, a line curves towards the mouse from different starting points. The line will be of random width, color, and thickness. It kind of looks like a fireworks sparkler on the 4th of July. This type of mouse chaser is way too frenetic for the main part of a movie but is an excellent device to add to a preloader. The curving line will keep your visitors entertained and occupied while the main site loads.
322
To create an ActionScript mask: 1. Create a movie clip symbol that you want to use as a mask. You can animate the movie clip if desired using motion tweening, frame-by-frame animation, or by using ActionScript to generate random motion. 2. Create a movie clip for the object that will be masked. This movie clip can be animated as well. However, youll get your best results if you mask a static image such as a vector graphic or a bitmap. 3. Open the document Library and drag an instance of the movie clip you want to mask onto the Stage. 4. Drag an instance of the movie clip that will serve as the mask onto the Stage. 5. With the mask movie clip still selected, click the arrow to the left of the word Properties to open the Property inspector. 6. Enter a name for the movie clip in the <Instance Name> field and close the Property inspector. 7. Select the movie clip that will be masked. 8. Click the arrow to the left of the word Actions to open the Actions panel. 9. Choose ObjectsMovieMovie ClipMethods and then double-click setMask. Two parameter text boxes appear above the Script pane. 10. In the Object field, type this The object is what is being masked. Because the ActionScript is being applied to the object being masked, the this alias can be used. If the ActionScript is assigned to a button, the absolute path to the movie clip needs to be entered in this field. 11. Place your cursor in the Parameters field and click the Insert a Target Path button to open the Insert Target Path dialog box. 12. Click the button that represents the movie clip you are using as a mask and then click OK to close the dialog box. When the movie is published, the animated movie clip mask will reveal the mask object. Figure 16-2 shows four frames of a movie clip mask in action. You can also create an ActionScript mask within a movie clip symbol. You do this by nesting the movie clip and the movie clip that will serve as a mask within a movie clip. Then its a simple matter of applying the ActionScript and choosing the right path, as shown in the following steps: 1. Create the movie clip that will serve as the mask as outlined previously. 2. Create a movie clip symbol for the object you want to mask as outlined previously.
323
Figure 16-2: You can create dazzling eye candy using the setMask action.
3. Choose InsertNew Symbol. The Create New Symbol dialog box appears. 4. Name the symbol, choose the Movie Clip behavior, and then click OK to enter symbol-editing mode. 5. Choose WindowLibrary to open the document Library. 6. Drag an instance of the movie clip symbol you want to mask onto the Stage. Use the Align panel to center the movie clip to Stage. 7. Drag an instance of the movie clip that youll use as a mask from the document Library to the Stage and align it to the center of the Stage. 8. With the movie clip still selected, click the arrow to the left of the word Properties to open the Property inspector. 9. Type mask in the <Instance Name> field and then close the Property inspector. 10. Select the movie clip that will be masked and then click the arrow to the left of the word Actions to open the Actions panel.
324
11. Choose ObjectsMovieMovie ClipMethods and then double-click setMask. Two parameter text boxes appear above the Script pane. 12. In the Object field, type this The object you are masking is the selected object; therefore, you can refer to it by the this alias. 13. Place your cursor inside the Parameters field and then click the Insert a Target Path button. The Insert Target Path dialog box opens. 14. Click the Relative radio button and then click the button that reads mask. Click OK to close the dialog box. 15. Click the Back button to exit symbol-editing mode. When you create an ActionScript mask in a movie clip symbol, you can use it anywhere in the document. You can have two or three instances of the ActionScript mask playing at one time, or you can create several movie clips where you use ActionScript to mask different objects. You can resize the movie clips to a different size as needed. Consider the effect you can achieve by having multiple instances of an animated mask movie clip on Stage, each clip a different size.
325
To display the mouse after it has been hidden: 1. Select the keyframe or object where you want to create the ActionScript to reveal the mouse. 2. Click the arrow to the left of the word Actions to open the Actions panel. 3. Click ObjectsMovieMouseMethods and then double-click show.
326
14. Click the button labeled cursor to add the target path of your cursor movie clip to the code and then click OK to close the dialog box. 15. Click the Lock Mouse to Center check box. Your finished ActionScript should look like Listing 16-3.
327
create this effect, you first create a movie clip with a motion tween animation in it. Then you use the duplicateMovieClip action to create the trails and modify each duplicated movie clips alpha property to create the fading effect. To create a motion trail: 1. Choose InsertNew Symbol. The Create New Symbol dialog box appears. 2. Choose the Graphic behavior and then click OK to enter symbol-editing mode. 3. Use the drawing tools to create an object or import a vector or bitmap image. 4. Click OK to exit symbol-editing mode. 5. Create another new symbol, this time choosing the Movie Clip behavior. 6. Choose WindowLibrary. The document Library opens. 7. Drag an instance of the graphic symbol into the movie clip symbol. 8. Create a motion tween animation. Vary the size of the object between keyframes. Motion paths also make good motion tween animations. 9. Click the Back button to exit symbol-editing mode. Figure 16-4 shows a motion tween animation created for a motion trail movie clip. After you create the motion tween animation, you nest it in another movie clip and the fun begins. The ActionScript to finish the motion trail effect uses three frames. The first frame initializes the variables, the second frame uses the duplicateMovieClip action to create the trails, and the third frame loops the animation. To complete the motion trail effect 1. Create a new movie clip symbol. 2. Choose WindowLibrary. The document Library opens. 3. Drag an instance of the motion tween animation you just created on Stage. 4. Open the Property inspector and in the <Instance Name> field, type clip 5. Create a new layer and label it actions. 6. Select the second and third frames and press F6 to convert them to keyframes.
328
Figure 16-4: A motion tween animation is the first step in creating a motion trail effect.
7. Select the third frame on the first layer and press F5 to create additional frames. 8. Select the first keyframe on the Actions layer and then click the arrow to the left of the word Actions. 9. In the left pane of the Actions panel, choose ActionsVariables and then double-click set variable. 10. In the Variable field, type loops and in the Value field, type 0 11. In the Value field, click the Expression check box. 12. Repeat Steps 8 thorough 10 to create a new variable. Name the variable trails and set its value equal to 12. Be sure to check the Expression check box in the Value field. The actual value you choose for trails is largely a matter of personal taste. The sample file in this chapters CD-ROM uses a value of 15. Experiment with different values to suit the design you are creating. 13. Select the second keyframe and in the left pane of the Actions panel, choose ActionsConditions/Loops and then double-click if. The Condition parameter text box appears above the Script pane. 14. In the Condition field, type loops<trails+1
329
15. In the left pane of the Actions panel, choose ActionsMovie Clip Control and then double-click duplicateMovieClip. The parameter text boxes appear above the Script pane. 16. In the Target field, type clip This is the instance name of the motion tween animation that will be duplicated to create the motion trails. 17. In the New Name field, type clip + loops Be sure to click the Expression check box. This line of code names the duplicated movie clips. 18. In the Depth field, type loops 19. Click ActionsMovie Clip Control and then double-click setProperty. 20. Click the triangle to the right of the Property field and choose _alpha(Alpha). The line of code will vary the opacity of the duplicate clips. 21. In the Target field, type clip + loops and click the Expression check box. 22. In the Value field, type 70-(loops*(50/trails)) This may look a little complex, but actually it isnt. Each duplicated movie clip becomes more transparent as the loop continues. The next line of code increases the value of loops by 1. 23. In the left pane of the Actions panel, choose ActionsVariables and then double-click set variable. 24. In the Variable field, type loops and in the Value field, type loops + 1 Your finished code should look like Listing 16-4. 25. Select the third frame and click the arrow to the left of the word Actions. The Actions panel opens. 26. In the left pane of the Actions panel, click ActionsMovie Control and then double-click goto. 27. Accept the default parameters and in the Frame field enter 2. Your ActionScript should read gotoAndPlay(2).
330
The heart of this effect is in the code you create on the second keyframe. This duplicates the motion tween animation movie clip and decreases the opacity of each duplicate. When you create this effect for your own designs, remember that you can swap the motion tween animation symbol with another to create a different effect. Just remember to name the instance of the new symbol, clip and the effect plays without a hitch. You can also vary the effect by changing the number of trails and the beginning alpha value. Instead of using 70 as the base alpha for the effect, try a lower or higher value. Figure 16-5 shows a movie that uses the motion trail effect to good effect.
Figure 16-5: You can add excitement to your designs with the motion trail effect.
On the CD-ROM
To view an example of a motion trail movie, copy to your hard drive the motionTrails.fla file that you find in this chapters folder on the CD-ROM that accompanies this book. Use your computer operating system utilities to disable the files read-only attributes and launch the file in Flash. Choose ControlTest Movie to see the effect.
331
Unfortunately, the number of steps involved in creating this effect are quite numerous. Rather than have you read a lengthy tutorial, the steps that follow dissect the ActionScript used to create the effect.
On the CD-ROM
To learn how to create a starburst backdrop, copy to your hard drive the randomStars.fla file found in this chapters folder on the CD-ROM that accompanies this book. Use your operating system utilities to disable the files read-only attributes.
To learn how the starburst backdrop effect is created: 1. Launch Flash and open the randomStars.fla file. 2. Choose ControlTest Movie. Flash publishes the file and plays it in another window (see Figure 16-6).
Figure 16-6: You can use ActionScript to create a starburst background like this.
As the movie plays, you see what appears to be an ever changing field of stars. In reality, its only one movie clip duplicated over a hundred times. The entire file is only 155 KB, dainty by any designers standards. You can use this file or a similar one of your own creation for an interesting backdrop. To see how the effect is created, close the window and follow the upcoming steps.
332
1. Click the small white dot in the upper-left corner of the movie and choose EditEdit Selected. Flash enters symbol-editing mode. The entire movie clip is only two keyframes long. 2. Click the arrow to the left of the word Actions to open the Actions panel. 3. Click the small white dot just above the center of the Stage. This is a small circle nested in the movie clip. Listing 16-5 shows the ActionScript that is used to set the initial position of the movie clip.
When the movie clip first loads, the _x and _y properties of the movie clip are set to random positions. The value of 540 for the _x was chosen to keep the movie clip within the boundary of the movie. The value of 280 for the _y property was chosen to keep the stars above the orange part of the background, which is a gradient blend created with the Color Mixer. The fourth line of code generates a random value for the _xscale of the movie clip, and the fifth line of code sets the _yscale equal to the _xscale so the movie clip resizes proportionately. The next line of code varies the opacity of the movie clip. The conditional statement sets the _alpha property equal to 50 if the random value generated drops below 50. This statement was entered to prevent the movie clip from blending into the background. The desired effect was to simulate twinkling stars; an alpha value less than 50 would cause the stars to all but disappear. To see the code used to create the rest of the effect, click the first keyframe. If you still have the Actions panel open, you see the code in Listing 16-6.
333
The first line of code declares a variable named k and sets it equal to 0. The second line of code initializes a variable named i and sets its value equal to a random number between 1 and 200. The third line of code initializes a while loop. While the value of k is less than i, the movie clip is duplicated. The movie clip is duplicated each time it loads and new random values are generated, which simulates the appearance of a star on another part of the Stage. The next line of code increments the value of k by 1. The loop continues creating duplicate stars until the value of k exceeds i. After the loop finishes, the movie clip plays frame 2 which has a goto action that returns it to frame 1, whereupon the whole process repeats itself and a new field of stars is generated. However, theres one additional item on the second frame that pauses the movie so the viewer can see the stars. Click the small white dot below the center of the Stage. This is a user-defined component that contains nothing but ActionScript. The component pauses the movie. You could pause the movie by adding a few frames between the keyframes. However, if you ever needed to change the effect, youd have to add or delete frames. Also, with a given number of frames, the effect would be too predictable. The user-defined component is a timer that pauses the movie for a different amount of time every time the frame plays. With the component still selected, click the arrow to the left of the word Properties to open the Property inspector. The component has only one parameter: Seconds (shown in Figure 16-6). The ActionScript in the component pauses the movie for a random amount of time up to the value entered in the Seconds field. To see how the component works, click the number (.6) to the right of seconds and enter a higher value. Choose Control Test Movie. After Flash publishes the file, youll see that the stars dont change as quickly. Enter a smaller value in the seconds field, and a new star field is generated more quickly. You can create a similar effect by recreating the code in your own movie, or you can modify this movie to suit your needs by creating a different background or by creating a new movie clip symbol with a different graphic than a circle. Edit the starfield movie clip and swap the circle movie clip for your own symbol.
334
To follow along with this exercise, copy to your hard drive the slideShow.fla file you find in this chapters folder on the CD-ROM that accompanies this book. Use your computer operating system utilities to disable the files read-only attributes.
To dissect the code used to create the slide show movie: 1. Launch Flash and open the slideShow.fla file. 2. Choose ControlTest Movie. Flash publishes the movie and plays it in another window. When the movie begins, all you see are instructions for the user. 3. Move your mouse over the scroll left control and the images begin moving (see Figure 16-7). 4. Move your mouse farther to the left and the images move faster. Move your mouse toward the images and they stop moving so you can get a better look. Move your mouse over the scroll right control and the images move to the right, picking up speed as you move farther away from the center of the movie. After youve finished playing the movie, close the window. Now that youve seen the effect in action, its time to examine the code and see what makes this effect work. As shown in Figure 16-7, the actual movie consists of three keyframes and several layers. Theres a mask layer with an image the same size as the movie. By adding the mask, you can load this movie into a target window in a larger movie. The mask prevents the other images from being seen as they scroll past the edge of the movie. The actual image was created in an image editing program. Several individual images were combined to create the strip. The image was given an instance name of strip. To examine the code used to create this effect: 1. Click the arrow next to the word Actions to open the Actions panel. 2. Click the first keyframe on the Actions layer and you see the code shown in Listing 16-7.
335
Figure 16-7: The images in the slide show scroll across the screen.
The ActionScript in Listing 16-7 initializes the variables for the movie. The variable named center defines the center of the movie; rightBorder defines the end of the image strip. The leftBorder variable is equal to 0. The registration point is set to x=0 instead of the center of the film strip. The last variable, stripPos, is set equal to the _x property of strip, the instance name of the movie clip with the image. Figure 16-8 shows the movie clip with the image. Notice that the left side of the image is aligned to the center of the Stage. The image is 3496 pixels long, making its right border 3496.
336
Registration point
When the movie begins playing, the first frame sets up all the variables and then the second keyframe plays. The code for the second keyframe is shown in Listing 16-8.
337
Notice that the ActionScript consists of three conditional statements. The first conditional statement evaluates the _y property of the mouse. When the _y property of the mouse is greater than 250 (the top border of the scroll controls), the variable stripSpeed is set equal to the _x property of the mouse minus the value of center divided by 8. If you experiment with this effect, you can speed up the scrolling by choosing a value less than 8, or slow it down by choosing a value higher than 8. The variable center defines the center of the movie. This defines the speed and direction of the strip. The result was divided by 8 to slow the speed down. The next line of code sets the value for the variable stripPos. The first frame initialized the value of stripPos and set it equal to the _x property of the image strip. As the user moves the mouse to the left, the value of stripSpeed decreases. When this value is added to stripPos, it causes the strip to move to the left. When the user moves the mouse to the right, the value of stripSpeed increases and when added to stripPos, causes the image strip to move to the right. As the user moves the mouse farther in either direction, the speed increases. The next two conditional statements reset the value of stripPos in order to keep the film strip from scrolling out of the movie. The final line of code sets the _x property of the strip movie clip equal to stripPos. The third keyframe loops the movie back to the second frame so that the Flash Player can continually evaluate the position of the users mouse and move the film strip. When you need to create an effect like this for a client, all you need to do is change the value of the variable center to equal the center of your document (width/2) and change the value of rightBorder to the negative of the width of the image you are displaying. When you create the movie clip for the image, remember to align the left edge of the image to x=0. Alternately, you can import the image into the document, select it, and then click F8 to convert the image into a symbol. Choose the movie clip behavior and the middle left registration point and youre good to go.
Designer Notes
In this chapter, you learned to create some of the fun frilly things that make a Flash design a success. You learned to create a custom cursor and a mouse chaser, two items sure to keep your viewers entertained. You also learned to create the motion trail effect and create a custom background of twinkling stars. In the chapter project, you learned how to create the ActionScript needed to create a moving slide show. In the next chapter, youll learn to integrate Flash movies with your HTML designs.
17
C H A P T E R
In This Chapter
Creating a pop-up window Creating banner ads Detecting the Flash Player Creating a Flash introduction Chapter project: Creating an animated Flash banner
The Actions panels got lots of books. And some of these books have books within a book. To add some actions to your scripts, you have to click this book icon, then click that book icon, then click another book icon, and so on. Rather than bore you with a lot of words, Im going to show the path to each action as shown in the following example: Click ActionsMovie Control and then double-click goto.
340
window gives you control over the parameters of the pop-up window. You can specify the size of the window and whether the new window has scrollbars or not. To display a link in a pop-up window: 1. Select the button or keyframe that will cause the new window to pop up. 2. Click the arrow to the left of the word Actions to open the Actions panel. 3. Choose ActionsBrowser/Network and then double-click getURL. 4. In the URL field, type Javascript:newwin1 ( ) This bit of code tells the Flash Player that the URL for the link is located within JavaScript in the HTML document the movie is embedded in. 5. To create additional links that open in another window, repeat Steps 3 and 4, and in the URL field, type Javascript:newwin2, ( )Javascript:newwin3 ( ), and so on. After you publish the document as a Flash movie, you have to modify the HTML document the movie is embedded in to include the JavaScript that will open the link in a new window. To modify the HTML document: 1. In your HTML editor, open the HTML document the Flash movie is embedded in. Alternately, you can open the document in a text editor. 2. In the head of the HTML document, enter the JavaScript shown in Listing 17-1.
The JavaScript in the previous listing opens the link in a browser window 640 pixels wide by 480 pixels high. The window has scrollbars. When you create the JavaScript to open the new window, its always a good idea to size it smaller than the parent window. A desktop size of 800 pixels by 600 pixels seems to be the most popular these days. Therefore, if you size the pop-up window to 640 x 480, the HTML page with your Flash design is visible in the background. You can also use this technique to play your Flash design in an HTML document the exact size of the movie. To do this, you create two movies. The first movie has nothing but the getURL action with the Javascript newwin 1() code. In the
341
HTML page, you create the JavaScript to open the main movie in a new window called flashMovie.html that is sized to the movie. Listing 17-2 shows the code that will open the main movie in a sized window.
In the preceding code, you notice the HTML page with the Flash movie is referred to by its relative path. When the HTML document the movie is embedded in is in the same root directory, you can refer to it by name and extension. Also notice that the size of the Flash movie embedded in the HTML document that opens the main movie is only 1 pixel by 1 pixel.
342
too large to download quickly. This is where Flash has come into favor with Web designers. Using Flash, you can quickly create an impressive banner ad that downloads quickly into the users browser. But before you rush headlong into Flash and create the banner, consider where the banner will appear in your HTML design. Many Web designers display a single banner across the top of a page; other designers prefer to display one or more banner ads on the side of the page. Figure 17-1 shows a Flash banner across the top of a Web page.
Figure 17-1: You can display a banner ad across the top of an HTML page.
When you do decide on a position for the banner ad, keep the elements in your HTML design in mind. Stick with similar colors or the same colors that appear in your HTML design. You dont want your finished product looking like some of the cut and paste HTML designs that run rampant in the backwaters of the Internet. Figure 17-2 shows a Web page displaying ad banners on the side of the page. Another popular alternative is the pop-up ad that appears when a page loads or a button is clicked. Whether you decide to place your banner ad at the top or side of the page, theres no need to reinvent the wheel when you create the ad in Flash. Most of the popular layouts and sizes for banner ads are available as templates.
343
Figure 17-2: Many Web designers display banner ads on the side of a design.
To create a banner ad: 1. Launch Flash and choose FileNew from Template. Flash opens the New Document dialog box. 2. In the Category column, click Ads to display the Flash ad templates (see Figure 17-3). 3. Choose one of the presets. Flash opens the template, as shown in Figure 17-4. Notice the text in Figure 17-4. These are instructions and guidelines the designers of Flash have thoughtfully included with the template. They offer some good advice, such as keeping the file size of the initial load below 15K. The information is all on a guide layer. After you finish reading the information, delete the guide layer and youre ready to go to work. At the end of this chapter, youll be creating a small banner ad.
344
Figure 17-3: You can create banner ads from a preset template.
345
346
8. Type 4 This evaluates the fifth character in the version string. Remember that the first index of a string is 0. 9. Place your cursor the right of the last parentheses in the field and type ==6 How you finish the ActionScript depends on how you have structured your movie. Listing 17-3 shows ActionScript that loads one movie if Flash Player 6 is detected, another if Flash Player 5 is detected, and directs the viewer to an HTML version of the site if neither Player is detected.
Another option you may want to consider is creating an HTML page that welcomes viewers to the site and lists the Flash Player required to view the site and other necessary hardware. The page has two buttons, one that links viewers to the Flash version of the site and another that directs viewers to the HTML version of the site.
Tip
If you prefer, you can use some ready made Macromedia detection tools. Log on to the Internet and point your Web browser to: http://dynamic. macromedia.com/bin/MM/software/trial/hwswrec.jsp?product= flash_deployment_kit to download the Flash Deployment Kit.
347
Figure 17-5: You create an intro to whet the viewers appetite for an HTML site.
If your client runs television commercials, request copies of the images used in the commercial for use in the intro. You can then use some of the techniques presented in this book to add motion. If you have image-editing software at your disposal, create a strip of images and then have them move across the screen. Add another layer with highly transparent text moving in the opposite direction, and youve got a compelling intro. If you add music to your intro, use an interesting four-second music loop, play it four times, and youve got a 16-second intro. Alternately, you can loop the sound three times and then position another instance of the sound on the timeline four seconds before the intro ends. If you have a 16-second intro playing at 12 fps (frames per second), your timeline is 192 frames long. Place an instance of the sound on frame 144, open the Property inspector, click the arrow to the right of the Effect field, and choose Fade Out. When you publish the movie, the sound will fade out at the end of the intro. You should always include a Skip Intro button so viewers who have been to the site before have the choice of viewing the intro again or not. If you do your job correctly, new viewers to the site wont use the Skip Intro button. If you have no sound with your intro, program the Skip Intro button with the getURL action to launch the first page in the HTML site. However, if you have sound with your intro, the sound continues playing even though the intro is no longer playing. If you have a soundtrack on your intro, program the Skip Intro button as follows:
348
1. Create a symbol button symbol with text that reads something like <Skip Intro> and then place an instance of the button on Stage. 2. Select the Skip Intro button, click the arrow to the left of the word Actions. 3. Choose ActionsMovie Control and double-click goto. Code the ActionScript to go to and play the last frame of the intro. 4. Select the last frame of the intro and press F6 to convert it to a keyframe. 5. Click the arrow to the left of the word Properties to open the Property inspector. 6. Click the triangle to the right of the Sound field and choose your intro sound from the drop-down menu. 7. Click the arrow to the right of the Event field and then choose Stop. 8. Click the arrow to the left of the word Actions to open the Actions panel. 9. Choose ActionsBrowser/Network and then double-click getURL. 10. In the URL field, enter the path to your main HTML page. If the page is in the same directory as the movie, you need only enter the relative path, for example: homePage.html. 11. Choose ControlTest Movie. When your intro starts playing, click the Skip Intro button. The movie advances to the last frame and the sound stops playing. When you create a Skip Intro button for a movie with no soundtrack, you dont have to worry about advancing the movie to the last frame and then stopping the soundtrack. Therefore, all you have to do is create the button and then use the getURL action to load the main HTML page. When the button is clicked, the specified URL loads.
Tip
If you meet face-to-face with your clients and you have a small laptop, consider adding a directory to the laptop and storing some examples of your best Flash work in the directory. Create an HTML document with links to play the movies. Create a desktop shortcut to the HTML page, and you can demonstrate your work to the client. If a picture is worth a thousand words, a great Flash intro must be worth at least a million. A quick demonstration of your work can be the difference between getting a job on the spot or having your potential customer shop your quote with other designers.
349
the movie to the browser, open the HTML file in an HTML editing program such as Dreamweaver and center the movie. Each software program uses slightly different tools to achieve this. In Dreamweaver, you can place your cursor before the Flash movie, open the Property inspector, and click the Center alignment button. If you edit the document in software where you can work directly with the code, type the following tag before the Flash object: <div align=center>. Then type the following tag after the object: </div>. Listing 17-4 shows the HTML code for a Flash object that has been centered in an HTML page.
Notice the PLUGINSPAGE line in the previous listing. If the viewer doesnt have the Flash plug in and the users browser supports redirecting, the browser displays the warning that the Flash plug in is required to view the page and offers an option to redirect the viewer to the listed URL. If you integrate items such as banners and menus you create in Flash with your HTML pages, you can import them directly into an HTML document in Dreamweaver. Many designers find it convenient to nest a Flash banner or menu in an HTML table.
350
This gives you the most flexibility as you can size your table rows and columns around the Flash documents. From within Dreamweaver, you can select a table row or column and then choose InsertMediaFlash. Figure 17-6 shows a Flash movie in an HTML document being edited in Dreamweaver. When you select a Flash file within Dreamweaver and then open the Dreamweaver Property inspector, you can preview the file by clicking the Play button (refer to Figure 17-6).
Figure 17-6: You can insert your Flash work directly into an HTML document.
Dreamweaver also has built-in Flash objects. If youre working on an HTML document in Dreamweaver, you can add Flash buttons and Flash text on the fly. To add a Flash button to an HTML document from within Dreamweaver, choose InsertInteractive ImagesFlash Buttons to open the dialog box, as shown in Figure 17-7. To insert Flash text, choose InsertInteractive ImagesFlash Text. When you insert Flash text in a document, you can specify different font parameters than the rest of the document, select a background color, select a rollover color, and specify a link and target browser window. Figure 17-8 shows several examples of Flash buttons and text created in Dreamweaver.
351
Figure 17-7: You can insert a Flash button from within Dreamweaver.
Figure 17-8: You can add Flash interactivity to an HTML page from within Dreamweaver.
352
To follow along with this project, copy to your hard drive the animatedBannerBegin. fla file that youll find in this chapters folder on the CD-ROM that accompanies this book. Use your computer operating system utilities to disable the files read-only attributes.
To create an animated banner: 1. Launch Flash and open the animatedBannerBegin.fla file. Notice that the document has already been sized to 550 x 100, a typical size for a Web site splash banner. The banner is long enough and wide enough to attract attention and showcase your talent. You can incorporate the banner within a table that displays text and images below the banner. 2. Choose WindowLibrary. The document Library opens. 3. Open the Movie Clips folder and drag an instance of the corporateOfficers movie clip onto the Stage. 4. Using the Align panel, align the movie clip to the left corner of the Stage. 5. Drag an instance of the corpLogo symbol from the document Library onto the Stage. 6. Align the symbol to the center of the document. 7. Choose ControlTest Movie. Flash publishes the movie and displays it in another window. What youve just created is interesting enough. Theres a nice little animation playing in the corner along with a good-looking logo in the center of the banner. However, you can add so much more with just a bit of ActionScript. When youve finished looking at the movie, close the window to exit symbol-editing mode. To add a bit of excitement to the banner, youre going to add three fields of animated stars to the banner that move from left to right.
353
To finish the animated banner: 1. Choose WindowLibrary to open the document Library. 2. Drag an instance of the dark_star movie clip onto the Stage. If this looks somewhat familiar, it should. This is the same movie clip you used to create the mouse chaser in Chapter 15. 3. With the dark_star movie clip still selected, click the arrow to the left of the word Actions to open the Actions panel. 4. Choose ActionsMiscellaneous Actions and then double-click evaluate. The Expression field appears above the Script pane. 5. In the Expression field, type this._x-=5 This expression moves the movie clip to the left in increments of five pixels. However, when it reaches the end of the movie clip, it keeps on going unless you add a conditional statement. 6. In the left pane of the Actions panel, choose ActionsConditions/Loops and then double-click if. The action is added to the script, and the Condition field appears above the Script pane. 7. In the Condition field, type this._x<0 As soon as the movie clip moves beyond the left border of the movie, the next action is executed. 8. In the left pane of the Actions panel, choose ActionsMiscellaneous Actions and then double-click evaluate. The Expression field appears above the Script pane. 9. In the Expression field, type this._x=550 As soon as the movie clip moves beyond the left boundary of the Stage, this expression moves it back to the right side and it begins moving again. 10. Click the first line of code and in the parameter text box area, change the Clip Event to EnterFrame. Your finished code should resemble Listing 17-5. But wait, theres more.
354
11. Select the dark_star movie clip, and while holding down the Alt key (Windows) or Option key (Macintosh), drag down and to the left to create a duplicate instance of the symbol. Do this once more, this time dragging down and to the right. You should now have three instances of the movie clip on the Stage. 12. Select one of the duplicates and then click the arrow to the left of the word Actions to open the Actions panel. 13. Modify the existing code for the movie clip so the second line of code reads this._x-=7 14. Select the last duplicate and in the Actions panel, modify the second line of code to read this._x-=12 15. Choose ControlTest Movie. You should see three star fields moving across the banner at different speeds. As the star fields reach the end of the movie and reappear a time or two, eventually one starfield passes the other. If the motion is too frenetic for your taste, you can modify the ActionScript by choosing smaller values to make the star fields move more slowly. Figure 17-9 shows the banner tucked into a static HTML Page.
Figure 17-9: You can add excitement to a static HTML design with an animated banner.
355
Designer Notes
In this chapter, you were shown how easy it is to integrate Flash elements into your HTML designs. You learned how to open up a Web page in a different browser window from within a Flash movie. You learned to detect which version of the Flash Player your design is viewed with. And you also learned to create an intro for a static HTML page. Animated Flash banners were also presented, and the chapter project showed you how to spice up an HTML design with an animated splash banner.
A P P E N D I X
System Requirements
Make sure that your computer meets the minimum system requirements listed in this section. If your computer doesnt match up to most of these requirements, you may have a problem using the contents of the CD. For Windows 9x, Windows 2000, Windows NT4 (with SP 4 or later), Windows Me, or Windows XP: Intel Pentium processor (Pentium II or better) 64 MB of available RAM, 128 MB recommended 800 x 600, 256-color display (1024 x 768, millions colors recommended) 100 MB of free hard disk space Adobe Type Manager Version 4 or later with Type 1 fonts For Macintosh: Power Macintosh Processor (G3 or higher recommended) Mac OS 9.1 or later, MacOS X.1 or later
358
64 MB of available RAM 800 x 600, 256-color display (1024 x 768, millions of colors recommended) 100 MB of free hard disk space Adobe Type Manager Version 4 or later with Type 1 fonts
359
Whats on the CD
The following sections provide a summary of the software and other materials youll find on the CD. Shareware programs are fully functional, trial versions of copyrighted programs. If you like particular programs register with their authors for a nominal fee and receive licenses, enhanced versions, and technical support. Freeware programs are free, copyrighted games, applications, and utilities. Unlike shareware, these programs do not require a fee or provide technical support. GNU software is governed by its own license, which is included inside the folder of the GNU product. See the GNU license for more details. Trial, demo, or evaluation versions are usually limited either by time or functionality (such as being unable to save projects). Some trial versions are very sensitive to system date changes. If you alter your computers date, the programs will time out and will no longer be functional.
Author-created materials
All author-created material from the book including code listings and samples are on the CD in the folder named Author. In this folder youll find all of the raw materials for each chapter project, as well as the finished project. Youll also find other goodies such as user-defined components that you can drag and drop into your designs. Where applicable, youll also find a file that contains the finished project. These files are appended by _final.
Applications
The following applications are on the CD:
Acrobat Reader
Freeware Version. This program lets you view and print the Portable Document Format (PDF) files like the files on this CD. To find out more about using Adobe Acrobat Reader, choose the Reader Online Guide from the Help menu, or view the Acrobat.pdf file installed in the same folder as the program. You can also get more information by visiting the Adobe Systems Web site at www.adobe.com.
Macromedia Dreamweaver
If you want an idea of the magic you can include in your Web designs, check out this trial software. You can include sophisticated behaviors in your designs without having to cloud your mind with the first bit of JavaScript. You can also easily incorporate your Flash work in Dreamweaver.
360
Macromedia Fireworks
If you have the need for sophisticated image editing software that allows you to optimize graphics for the Web, Fireworks is the tool for you. You can combine vector graphics and bitmaps to create a sophisticated design that you can export as HTML and images, complete with all the JavaScript needed to pull off the effects you use.
Macromedia FreeHand
If you like to create sophisticated vector graphics, and find that the Flash tools as good as they are fall a bit short, give FreeHand a try. FreeHand makes it possible for you to create complex vector graphics and export them in Flashs native *.SWF format.
Swift 3D
Swift 3D is the solution youre looking for to add three-dimensional vector objects to your Flash movies. Swift 3D is a Windows/Macintosh application that you use to create and convert 3D images and animations to 3D vector graphics. Swift 3D exports the completed file in the Flash SWF format. Please visit Electric Rains Web site at www.electricrain.org for the latest updates on this product.
WildForm SWfx
SWfx is an easy-to-use text animation tool. You can choose from over 200 different effects to create swirling text, swooping text, and fading text, to name a few. The animation you create is exported in Flashs native SWF format. Use animated text to spice up your Flash designs.
Troubleshooting
If you have difficulty installing or using any of the materials on the companion CD, try the following solutions: Turn off any anti-virus software that you may have running. Installers sometimes mimic virus activity and can make your computer incorrectly believe that it is being infected by a virus. (Be sure to turn the anti-virus software back on later.)
361
Close all running programs. The more programs youre running, the less memory is available to other programs. Installers also typically update files and programs; if you keep other programs running installation may not work properly. Reference the ReadMe.txt: Please refer to the ReadMe file located at the root of the CD-ROM for the latest product information at the time of publication. If you still have trouble with the CD, please call the Wiley Publishing Customer Care phone number: (800) 762-2974. Outside the United States, call 1 (317) 572-3993. You can also contact Wiley Publishing Customer Service by e-mail at techsupdum@ wiley.com. Wiley Publishing will provide technical support only for installation and other general quality control items; for technical support on the applications themselves, consult the programs vendor or author.
A P P E N D I X
Flash Resources
lash is extremely popular software. There is a plethora of information on the Internet about Flash. You can download tutorials, completed *.FLA documents, and music loops for your designs. There are also several ancillary, thirdparty plug-in manufacturers that feature interesting software you can use to enhance your designs. This software ranges from 2D animation programs to software that produces 3D animations in the *.SWF format. In this appendix, youll find the URLs for these sites and a brief description of what you can expect to find at the site. This appendix is divided into three sections: resources, sounds, and third-party applications.
Resources
The Internet seems to have as many resources for Flash as it does Flash Web sites. This is a good thing. You can never get enough information. The sites in this section begin with the Macromedia resource sites followed by additional resources, which are listed in alphabetical order.
Macromedia resources
When you need to find out about an application, what better source than the maker? In this section youll find Macromedia resources for Flash.
Macromedia Support
Macromedia offers extensive support for their flagship product at www.macromedia.com/support/flash. Here youll find in-depth support in the form of technical notes,
364
as well as tutorials prepared by Macromedia technicians. If youve run into a snag using ActionScript, chances are you can find a solution here.
ActionScript.org
If you want to know all about ActionScript, ActionScript.org (www.actionscript. org) is the site to visit. At this site youll find tutorials and other useful information about ActionScript.
Extreme Flash
At Extreme Flash (www.extremeflash.com), youll find tutorials in the beginning, intermediate, and advanced categories. You can also download source files to analyze the files of other Flash designers.
Flahoo
Flahoo (www.flahoo.com) has links to sites designed with Flash. The links are divided by category. When youre between assignments, check out some of the sites featured here to get your creative juices flowing.
Flash Academy
At Flash Academy (www.enetserve.com/tutorials), youll find another source for Flash tutorials. The site has three sections: tutorials, examples, and experiments.
Flash 5 ActionScript
Even though the current version of Flash is MX, you can still find some useful information at Flash5ActionScript (www.flash5actionscript.com). At this site, you can download source files and view examples of code.
365
Flash Kit
If youre looking for tutorials, sample *.FLA files, and a host of other information about Flash, youre sure to find a lot to pique your interest at this site (www. flashkit.com). In addition to tutorials, you can also download free music loops from this site. Sources files can also be found in abundance. Download them and dissect them at your convenience. If you download a source file from a previous version of Flash, Flash MX updates the ActionScript where needed.
Flash Magazine
For the latest information about Flash, point your Web browser to www. flashmagazine.com. The site features noteworthy news flashes about Flash plus other valuable information and resources about the software.
ProFlasher
ProFlasher (www.proflasher.com) features several forums where you can gain valuable information about Flash from other designers and developers. There is a link where you can request tutorials, a link where you can request a review of a site you are creating, a link devoted to ActionScript, and much more.
TurtleShell.com
At turtleshell.com (www.turtleshell.com/2000), youll find resources and inspiration. The graphics are vector-based, and the author of the site uses them to good effect. When you click on a link, the vector shapes move and resize. This is the 2000 version of the site, which is still at the server. After you finish marveling the construction of the site, check out the Creation section, which features tutorials and other goodies. The main site (www.turtleshell.com) is undergoing a revision as this is being written. By the time you have this book in your hands, it may be up and running.
Virtual FX
The Internet seems to be a never-ending source of Flash information. Virtual FX (www.virtual-fx.net) features a tutorial search engine, source files, sample movies, and more. The source files and tutorials are currently in Flash 5 or earlier format. However, in a short matter of time, theres bound to be Flash MX source files and tutorials at this site. There is also a message board where you can communicate with other Flash designers.
Web Monkey
Web Monkey has a section of their site devoted to Flash. The URL is hotwired. lycos.com/webmonkey/multimedia/shockwave_flash. Here youll find tutorials and information about the application. You can subscribe to Web Monkey and have this valuable resource delivered to your via e-mail on a regular basis.
366
Sounds
Sound has become a very important element in Flash designs. You can add background music to your Flash designs and use sound effects for buttons or timeline events. The sites in this section feature loops you can purchase or download for free and software applications you can use to create your own sounds.
GrooveMaker
Heres another site (www.groovemaker.com) that offers impressive sound mixing software. Available for both Windows and Macintosh platforms, this software can be controlled with an external midi-controller or keyboard. You can render the sounds you mix in the popular MP3 format.
Killer Sound
At this site (www.killersound.com), you can purchase royalty-free music for use in your Flash designs. Choose from a number of musical genres from classical to jazz and then preview the music while online.
Sonic Foundry.com
If your clients require sophisticated background music and other sounds, you can create your own background music with the software available at this site (www. sonicfoundry.com). Sonic Foundrys Acid Music is resampling software. The software features a timeline similar to that found in Flash. You can arrange sound samples on the timeline to create unique music loops. You can also purchase libraries of sound samples at this site in a wide variety of genres from hip-hop to classical. You can render your creation in a wide variety of sound formats. This software is only available for the PC.
367
Sonic Foundry also features a program called Sound Forge. You can use Sound Forge to record sounds or modify sounds with sophisticated effects like echo and reverb. This software is only available for the PC.
Sound Shopper.com
If you need royalty-free music loops, buttons sounds, or other sounds for your designs, youll find a wide variety at this site (www.soundshopper.com). You can preview the sounds while online. The sounds are sold in bundles and priced quite reasonably.
Sound Strike
Soundstrike.com (www.soundstrike.com) offers free sound loops for download and other loop packs you can purchase. You can also purchase a bundle of button sounds.
Third-Party Applications
Flash is such a popular application, everyone seems to want a piece of the pie. There are several very useful applications you can use to enhance your designs. In this section, youll find a brief description of the type of software offered by the vendor, plus the URL to the Web site where you can purchase the software, download a demo version, or find out more information about the application.
Electric Rain
At this Web site (www.electricrain.org), youll find several solutions for including 3D artwork in your designs. Their main product, Swift 3D2.0, is used to create animations of 3D objects. The completed projects can be exported as .SWF movies. They also produce plug-ins for popular 3D software, that are used to generate *.SWF Movies from 3D animations and scenes created in the 3D application.
FlashJester
FlashJester (www.flashjester.com) features interesting products that you can use to augment your work. At this writing, all of their software is being updated to support Flash MX.
Flax
Flax (www.flaxfx.com) is another third-party program you can use to add text effects to your Flash work. You can choose from 31 effects that you can tweak using sliders and buttons. When the effect is the way you want it, you can export the file as a *.SWF file for inclusion in your design.
368
Sorenson
At Sorenson (www.sorenson.com), you can download a copy of Squeeze, which is software for compressing video files into the *.FLX format for importing into Flash or as an *.SWF movie. The software has settings for different connection speeds and does an admirable job of producing a small file size with the least amount of image degradation possible for the intended connection speed.
Swish
If you like text effects, Swish (www.swishzone.com) offers a relatively inexpensive program that you can use to add animated text to your designs. The site offers tutorials and support for Swish users.
Wildform.com
At this Web site (www.wildform.com), you can purchase a standalone program called SWfX that you can use to create some interesting text effects for your productions. The site also features a useful resources section with informative tutorials and source files for download.
A P P E N D I X
Flash Inspiration
ome days the creative juices flow like the headwaters of a clear mountain stream; other days, theyre stagnant like a slow river in the heat of summer. When you find your creativity is at a low ebb, you can find inspiration at many of the sites listed in this section. Each site uses Flash in a unique or artistic way to create a compelling site that keeps visitors returning. When youre at a loss for what to do or you simply want to explore a site thats visually exciting, visit one of the sites listed in this appendix. Begin your journey at Macromedias site of the day and branch out from there. If the site lists the URL or a link to the designers Web site, visit that site for more inspiration. You can also find Flash sites by typing Flash into your favorite search engine. The sites in this appendix begin with Macromedias site. The sites that follow are listed in no particular order, which is probably the way you look find inspiration on the net in no particular order.
Eva Hesse
This site (www.sfmoma.org/hesse) uses Flash to explore the work of Eva Hesse. During the 60s, this artist created sculptures and paintings. The site is informative and features an interesting navigation system.
370
Madonna
This popular singers Web site (www.madonna.com) features an innovative navigation system. Move your cursor over one of the moving images and then drag down. When the three images line up, a different song is loaded.
John Frieda
At John Friedas site (www.johnfrieda.com/flash.htm), youll find links to two excellent Flash productions: Sheer Blonde and Relax. Both movies promote hair products and combine an excellent use of text drop-down menus with bitmap images. The Sheer Blonde side of the site features an intro song and the models used to promote the products are easy on the eyes.
n.fuse.gfx
This site (www.nfusegfx.com) gives the viewer the option of choosing a lowbandwidth or high-bandwidth site. Both options provide excellent eye candy, intriguing background music, and an interesting navigation system.
Pepworks.com
This title bar for Pepworks.com (www.pepworks.com) advertises designs, games, and fun. The site has a compelling introduction. Click the Leos Great Day button for an example of an excellent Flash game.
371
Juxt Interactive
Juxt Interactive (www.juxtinteractive.com) has designed some of the more innovative Flash sites in existence today. Their own site is a perfect example of this. They provide an excellent balance of stationary and animated graphics along with an interesting drag-and-drop navigation system in their portfolio section. You can launch some of their impressive designs right from the portfolio section.
Lenny Kravitz.com
Lenny Kravitzs Web site (www.lennykravitz.com) has an animated preloader, a pop-up navigation menu, and a jukebox that fans can use to preview the musicians latest work. The movie loads quickly despite a heavy use of bitmap images.
Jaguar X Type
Jaguar.com (www.jaguar.com.au), an Australian Web site, uses Flash to introduce the manufacturers new model. After the movie loads, move your mouse around the screen and a movie clip with an animation follows. The animation changes size as you move it around the screen, an effect no doubt achieved by altering the properties of the movie clip that houses the animation.
Velocity Studio
At Velocity Studio (www.velocitystudio.com), youll find a unique preloader. The site features a stunning use of bitmap images and a unique navigation menu that seems to actively defy your attempts to choose a button and then click it.
372
Andy Foulds
Photographers Web sites always seem to be the epitome of good taste and this one (www.foulds2000.freeserve.co.uk) is no exception. Entertain yourself with one of the amusements while the main site loads. After the main site loads, click a link to view examples of Andys photography or Web designs.
Tweened.com
After this site (www.tweened.com) loads, use your arrow keys to navigate the site. A cute little animated cartoon figure jumps up and down when you press the Up arrow key and crouches when you press the Down arrow key. When you roll your mouse over the character, a bubble pops up with a saying. Do it once too often and the saying in the bubble informs you that the character is ignoring you and ceases to recognize your existence.
Pray Station
At praystation.com (www.praystation.com), you can view the online Flash explorations of Joshua Davis. Click a link in the left window to experience some very compelling visual effects. The effects in this site feature some very sophisticated ActionScript. Take a look at the animations and see if you can figure out how they were created.
373
Audi A4 Avant
Audi uses Flash to introduce the Audi A4 Avant (www.audi-a4.com/avant/ a4_avant.html). The sites preloader features bitmap images. Tasteful background music and an intriguing navigation menu are a few of the features youll find here.
John Coltrane
The life of legendary musician John Coltrane (www.johncoltrane.com) is portrayed through the use of Flash. The quick loading site features another example of an innovative navigation device, similar to the flyout menu project in Chapter 10, yet done entirely with text.
Index
SYMBOLS
* (asterisk) with random method, 109 , (comma) separating array elements, 153 {} (curly braces) for statements in code, 38 . (dot) as separator in code, 38, 39 // (forward slashes) for comments, 3839, 70 ( ) (parentheses) for parameters in code, 38, 39 (quotation marks) for string literal data, 143 ; (semi-colon) as end of line identifier, 38, 39 Actions book. See also specific books and actions Browser/Network book, 23 Conditions/Loops book, 24 Miscellaneous book, 24 Movie Clip Control book, 2324 Movie Control book, 22 overview, 2124 Printing book, 24 User Defined Functions book, 24 Variables book, 24 Actions command (Window menu), 27 Actions layer, creating, 6970 Actions panel action books in, 1920 adding actions to your script, 29 context menu, 37 deleting actions from your script, 31 Designer panel layout and, 27 expert mode, 28, 35, 36 Find and Replace button, 33 Find button, 33 Insert a Target Path button, 130 modes, 28, 35 Move the Selected Actions Down button, 31 Move the Selected Actions Up button, 31 normal mode, 28, 35 opening, 27 Options menu, 3536 overview, 2021 Pin Current Script button, 32 Reference panel, 4, 17 Scene button, 191 Script pane, 21 setting breakpoints in, 289 switching modes, 35 using with other panels, 28 viewing options, 35 ActionScript. See also code; debugging; scripts as design element, 1214 HTML design versus, 52 JavaScript versus, 89 overview, 812 questions to consider, 1617 uses for designers, 47 ActionScript loops. See loops ActionScript objects. See objects ActionScript.org site, 364 AIFF sound format, 258 alias for target path, 132 Allen, Rob, 370 _alpha property, 44, 48, 169 anchors, named, 189, 193194 AND operator, 158159 Andy Foulds Web site, 372 animated buttons animating the label, 200203 creating movie clip for, 200 nesting the movie clip in a button symbol, 203204 uses for, 199 animated Flash banner project adding motion to the banner, 353354 creating the banner, 352 overview, 352 animated preloader. See preloaders animatedBannerBegin.fla file, 352 animation animated buttons, 199204 animated Flash banner project, 352354 animated preloader, 298306 for drag-and-drop elements, 238 interactive animation project, 183187 uses for, 14 applications on CD-ROM, 359360 arithmetic operators, 145, 147 Arithmetic Operators book, 24 Array user-defined component type, 132 arrays accessing, 161163 associative, 154155 combining elements in a variable, 152 comparing multiple values to, 151152 creating, 152153 creating elements for, 153154 overview, 6, 151 for populating dynamic text boxes, 224225 for random quote generation, 160 ticker text marquee project, 225230 uses for, 6 using word processor to create data, 154, 160 variables versus, 151152
A
absolute mode for target path, 130, 131 Acrobat Reader (on CD-ROM), 359 action books. See also specific books expanding to display actions, 22, 23 path to actions, 1920 actions. See also specific actions and books adding to your script, 29 assigning to buttons, 7, 7475, 9196 assigning to keyframes, 7, 29, 7071 assigning to objects, 29, 8791 compatibility issues, 26 deleting from your script, 31 deprecated, 26 designation for frames with actions assigned, 69 displaying information about, 3435 drop-down menu, 29 expanding books to display, 22, 23 finding using Index book, 4, 26 for Flash Player, 30 hierarchy, rearranging, 31 learning as you need them, 21 looking up in Reference panel, 34 for navigating, 7680 overview, 10 parameter text boxes for, 30 path to, 1920, 51 Reference panel for, 17 reserved keywords, 4041
376
Index AC
artwork. See graphics; movie clips AS-02Start.fla file, 45 .asf files, 84 Assets folder, 5859 assigning actions to buttons, 7, 7475, 9196 to keyframes, 7, 29, 7071 to objects, 29, 8791 associative arrays, 154155 asterisk (*) with random method, 109 attaching a sound, 269270, 276, 277 attachSound method of Sound object, 270, 276 Audi A4 Avant Web site, 373 audio. See Sound object; soundtracks .avi files, 84
B
bandwidth. See also preloaders analyzing movies with Bandwidth Profiler, 299301 analyzing movies with Show Streaming command, 301302 defined, 298 playing movies and, 298 preloader for large movies, 298 Bandwidth Profiler, 299301 Bandwidth Profiler command (View menu), 299 banner ads animated Flash banner project, 352354 creating, 343344 overview, 341342 planning, 342 banner.swf file, 136 base movie contents of, 120 creating, 121 for hiding your designs or techniques, 138 level of, 121 loading movies into, 121, 123125 unloading movies, 123, 124125 Billabong Web site, 370 bitmaps nesting in movie clips, 100 swapping nested bitmaps, 100, 101102 black (syntax coloring), 39 Blank Keyframe command (Insert menu), 68 blank keyframes. See also keyframes converting standard frames to, 68 creating, 68 for movie clips, 83
removing content from keyframes, 68 timeline designation for, 66 uses for, 68 blue (syntax coloring), 39 BODMAS acronym for operator precedence, 146 books. See action books; specific books Boolean data variables, 142 Boolean expressions defined, 53 for down arrow, 219221 for On When Pressed button, 196 for password evaluation, 53, 159 using, 159 Boolean user-defined component type, 133 breaking movies into segments. See also scenes base movie, 120, 121 dimensions for segment movies, 121, 125 levels for movies, 121 naming section movies, 123 planning, 120 template for section movies, 121123 uses for, 119120 breakpoints buttons for, 291 debugging a movie with, 290292 deleting, 291292 setting in Actions panel, 289 setting in Debugger, 291 storing, 290, 291 with trace action, 290 Brendan Dawes-Digital Creative Web site, 364 Browser/Network Control book. See also specific actions getURL action, 7780, 339, 340, 347, 348 loadMovie action, 123124, 125, 127129, 138, 267 loadVariables action, 216, 217, 218219 overview, 23 unloadMovie action, 123, 124125, 267 browsers. See Web browsers button.fla file, 96 buttonPhotography.fla file, 114 buttons ActionScript uses for, 7, 12 animated, 199204 assigning actions to, 7, 7475, 9196
CEO button, 138 to change size and opacity of movie clip, 4449 copying code between, 204, 206 creating, 7273 End of Page button, 221 Event Sync option for sounds, 260 frames for, 72 invisible, 74, 75 Key Press event for, 9394 layers for, 72, 73 mouse events, 9, 42, 75, 9294 multiple events for, 9293 for navigation, 95 nesting movie clips in, 203204 On When Press button, 194196 play action with, 76 Reset button for Flash forms, 308 rndFrame action with, 116117 rollOver and rollOut events for, 93 Skip Intro button, 260, 347348 for sound controller project, 275276 states, 7374 Submit button for Flash forms, 308310 swapping labels for, 198199 symbol, 42 for tooltips, programming, 237238 for user-customizable interface, programming, 242243 uses for, 81
C
call function action, 112113,
237, 243 calling functions, 112113, 116117 CD-ROM animatedBannerBegin.fla file on, 352 AS-02Start.fla file on, 45 button.fla file on, 96 buttonPhotography.fla file on, 114 colorComponents.fla file on, 179 contents, 359360 currentDate.fla file on, 247 currentTime.fla file on, 249 dragNdrop.fla file on, 240 drawOutside.fla file on, 60 eCommerce.fla file on, 312 flyoutMenu.fla file on, 204 interface.fla file on, 241 Jittery.fla file on, 199 marqueeComponent.fla file on, 230 mouseChaserBegin.fla file on, 316
Index C
377
movingNavBar.fla file on, 251 Orgchart folder on, 136 orgChart.fla file on, 136 randomStars.fla file on, 331 rndQuote.fla file on, 160 scrollText.fla file on, 217 scrollText.txt files on, 217 scrollTick.fla file on, 225 simpleChaserBegin.fla file on, 318 slideShow.fla file on, 334 Soundcontroller folder on, 274 submarine.fla file on, 183 system requirements, 357358 technical support, 361 toolTips.fla file on, 238 troubleshooting, 360361 centering Flash objects on HTML page, 349 CEO button, programming, 138 ceo.jpg tile, 137, 138 CGI script for HTML mail forwarding, 308309 character options, setting, 212213 child movie clips, 131 Clear Keyframe command (Insert menu), 68 clients, knowing expectations of, 55 clip events. See also events available events, 8889 defined, 9 overview, 8788 code. See also debugging; scripts copying between buttons, 204, 206 editing in expert mode, 36 formatting, 3839 hints in expert mode, 40 identifiers in, 3839 process of creating, 19 reserved keywords, 4041 syntax coloring, 37, 39 code handlers, 9. See also events code hints in expert mode, 40 Color object creating, 175 methods of, 175 setRGB method, 175176, 244 setTransform method, 174180 Color user-defined component type, 133 colorComponents.fla file, 179 colors Color object, 175180 random, for mouse chaser, 319 reserved keywords warning, 40 syntax coloring, 37, 39 user-customizable interface, 241245
Coltrane, John, 373 combining array elements in a variable, 152 contents of variables, 143144, 150 comma (,) separating array elements, 153 comment action, 293 comments adding to ActionScripts, 293 for debugging ActionScripts, 292293 forward slashes for, 3839, 70 for keyframes, 70 Common Libraries command (Window menu), 113 Common Libraries menu, adding effects Libraries to, 113 communicating between timelines, 129130 Comparison Operators book, 2425 compatibility deprecated actions and, 26 detecting Flash Player version, 345346 Flash Player versions and, 26 competitor URLs, researching, 55 Component Definition dialog box, 132134 components in colorComponents.fla file, 179 Flash UI Components book, 26 in marqueeComponent.fla file, 230 overview, 43 ScrollBar component, 249250 symbol, 43 user-defined, 132135 concatenating variables, 143144, 150 conditional statements. See also if action for animated button label, 202 Boolean expressions in, 53, 159 to change rotation, 202 controlling the flow of a movie, 53 creating, 156 defined, 11 for detecting Flash Player version, 344, 345 example, 11 for Flash slide show project, 336337 for Key objects, 181182 logical operators with, 158159 multiple outcomes for, 156157 overview, 24, 155156 for password evaluation, 53 for preloaders, 305, 306
Conditions/Loops book. See also conditional statements; if action; loops else action, 47, 156157, 253 elseif action, 156157 for action, 105 overview, 24 constants, 25 Constants book Down constant, 184 overview, 25 Up constant, 184 context menu of Actions panel, 37 Control menu Debug Movie command, 286, 291 Test Movie command, 49, 163 controlling the flow of Flash movies, 5354 Convert to Blank Keyframes command (Modify menu), 68 Convert to Keyframes command (Modify menu), 68 Convert to Symbol command (Insert menu), 98, 205, 232, 252, 280 Convert to Symbol dialog box for graphics, 98, 99 for movie clips, 280 for navigation bar, 205, 252 for tooltip shapes, 232 converting buttons to movie clips, 252 graphics to a symbol, 98, 99 movie clip to symbol, 280 movie clips to masks, 6062 navigation bar to a symbol, 205 navigation bar to flyout menu, 205208 standard frames to keyframes, 68 timeline animation to movie clip, 9899 tooltip shapes to symbols, 232 Copy Frames command (Edit menu), 98 copying. See duplicating Crazy Raven Productions Web site, 364 Create New Symbol dialog box for button templates, 197198 for buttons, 72, 194195, 203204 for label templates, 197 for movie clips, 82, 99, 200, 311, 323, 327 createEmptyMovieClip method, 320 curly braces ({}) for statements in code, 38 currentDate.fla file, 247
378
Index CE
_currentframe property, 169 currentTime.fla file, 249 curveTo Drawing method, 321 Custom Modem Settings dialog box, 301 Customize command (Debug menu), 201
D
dark_star movie clip, 316, 353, 354 Data event, 89 Date object creating, 245 displaying current date using, 246247 displaying current time using, 247249 example files on CD-ROM, 247, 249 methods for dates, 246 methods for times, 247248 retrieving date from host computer, 246 uses for, 14 Davis, Joshua, 372 Debug menu Customize command, 201 List Objects command, 287 List Variables command, 288 Debug Movie command (Control menu), 286, 291 Debugger breakpoints with, 290292 displaying list of movie objects, 287 launching, 286 overview, 285286 watching a variable, 286287 debugging ActionScripts breakpoints for, 290292 comments for, 292293 Debugger for, 285287 Movie Explorer for, 293, 294 need for, 283 testing your design, 284285 trace action for, 288289 decision making. See conditional statements declaring variables basic process, 148149 local variables, 149150 Default user-defined component type, 132 deleting actions from your script, 31 breakpoints, 291292 content from keyframes, 68 frames, 68 parts of code in expert mode, 36 scenes, 191192 undoing, 42
demo versions of programs, 359 deprecated actions, 26 Deprecated book, 26 Designer panel layout, 27 detecting Flash Player version, 345346 ready-made Macromedia tools for, 346 DirectX, video files supported by, 84 displaying. See also hiding and showing actions information, 3435 current date, 246247 current time, 247249 expanding action books to display actions, 22, 23 line numbers in scripts, 35, 290 link in pop-up window, 340 list of movie objects with Debugger, 287 list of variables with Debugger, 288 number of bytes loaded, 306 Distribute to Layers command (Modify menu), 234 do while loops, 103, 106107 Document command (Modify menu), 266 document Library creating button templates using, 198199 creating movie clip instances from, 86 gathering assets from, 59 opening .FLA files as, 59 overview, 4344 storing effects embedded in movie clips in, 113 storing user-defined components in, 134135 using symbols from, 43, 100 working with sound from, 268269 Document Properties dialog box, 266 dot (.) as separator in code, 38, 39 down arrow for scrolling, 219221 Down button state, 74 Down constant, in interactive animation project, 184 downloading extensions, 59, 135 user-defined components, 135 Dox Thrash Revealed Web site, 371 drafting your design, 56 Drag Out event, 92 Drag Over event, 92 drag-and-drop elements closing a window, 240 creating a drag-and-drop window, 239240 example file on CD-ROM, 240
motion tween animation for, 238 startDrag action, 238, 239, 240 dragNdrop.fla file, 240 drawOutside.fla file, 60 Dreamweaver (Macromedia) on CD-ROM, 359 integrating Flash with, 348351 drop-down menus of action groups, 29 _droptarget property, 169 duplicateMovieClip action cloning movie clips using, 87 duplicating objects using, 182183 motion trails using, 326330 duplicating cloning movie clips, 87 code between buttons, 204, 206 frames, 9899 objects with
duplicateMovieClip
action, 182183
rollOut and rollOver events, 93
scenes, 192 .dv files, 84 dynamic text boxes creating, 211212 displaying current date in, 246247 displaying current time in, 248249 options, 212 in organizational chart project, 135, 138 populating with array elements, 224225 rich formatted text for, 213215 scrolling text box project, 217223 scrolling text box using ScrollBar component, 249250 setting character options, 212213 ticker text marquee project, 225230 uses for, 209210
E
e-commerce catalog project, 312313 eCommerce.fla file, 312 Edit Envelope dialog box, 261262 Edit menu Copy Frames command, 98 Edit Selected command, 239 Paste Frames command, 99 Paste in Place command, 252 Undo command, 42 Edit Selected command (Edit menu), 239 editing code in expert mode, 36 sound characteristics, 261262 symbols, 42
Index EF
379
effects custom effects for sounds, 260262 free sound effects, 366 movie clips as effects modules, 113 for soundtracks, 259, 260262 storing in document Library, 113 Electric Rain Web site, 367 else action adding to script, 47 in conditional statements with multiple outcomes, 156157 in moving navigation bar project, 253 elseif action, 156157 e-mail forwarding, CGI script for, 308309 e-mail links, creating, 216217 embedding fonts, 213 embedding video files in movie clips, 84, 85 empty movie clip, creating, 320 End of Page button, 221 EnterFrame event, 89 erasing. See deleting error messages and warnings. See also debugging ActionScripts for incorrect variable names, 40, 148 for loops unable to execute in single frame, 103 <not set yet>, 47, 90 eval action, 155 evaluate action for animating banner ad, 353 for animating button label, 201202 for down arrow, 220221 expressions using, 172 in interactive animation project, 184185 in moving navigation bar project, 253254 evaluation versions of programs, 359 event handlers. See also on (Release) event handler for button symbol, 42 for movie clips, 89 Event Sync option, 260 events clip events, 9, 8789 defined, 81 mouse events, 9, 42, 75, 9294 for objects, 8889 overview, 9 plain English for planning, 57 sound events, 259260 triggering at sound completion, 273274
evolution of an ActionScript, 5254 expanding books to display actions, 22, 23 expert mode code hints in, 40 creating ActionScripts in, 36 described, 29 formatting code in, 3839 identifiers, 3839 switching from normal mode, 35 syntax coloring in, 37, 39 Export as File command (Options menu), 41 exporting scripts, 41 sounds, settings for, 263265 expressions Boolean, 53, 159, 196, 219221 for changing properties by given value, 172 creating mathematical expressions, 145146 defined, 143 in moving navigation bar project, 253254 operator precedence for, 146 overview, 144 extensions, 59 Extensions Manager, 59 Extreme Flash Web site, 364 eye candy custom mouse cursor, 325326 Flash slide show project, 334337 hiding and showing the mouse cursor, 324325 motion trails, 326330 mouse chaser using Flash MX object, 318321 mouse chaser using movie clip, 315318 movie clip as mask, 321324 overview, 13 starburst backdrop, 330333
F
file formats supported sound formats, 258 supported video formats, 84 File menu Import command, 58, 84, 259 New from Template command, 343 Open as Library command, 59, 113, 134 Publish Settings command, 193, 266 Save As command, 123 Find and Replace button (Actions panel), 33
Find button (Actions panel), 33 Find command (Options menu), 33 Find dialog box, using, 33 finding actions using Index book, 4, 26 and replacing text in a script, 33 text in a script, 33 Fireworks (Macromedia), on CD-ROM, 360 .FLA files, opening as libraries, 59 Flahoo Web site, 364 Flash 5 ActionScript Web site, 364 Flash Academy Web site, 364 Flash animations. See animation Flash Deployment Kit, 346 Flash forms creating elements for, 306307 example, 14 HTML forms versus, 297, 306 Reset button, 308 Submit button, 308310 Flash introduction, creating, 346348 Flash Kit Web site, 365 Flash Magazine Web site, 365 Flash movies. See also movie clips; planning your ActionScript movie; timelines analyzing for bandwidth problems, 299302 base movie, 120, 121 breaking into segments, 119123 controlling flow of, 5354 creating target movie clip, 125127 dimensions for segment movies, 121, 125 hiding your designs or techniques, 138 introduction movie, 346348 loading into base movie, 123124, 125 loading into target movie clip, 127129 navigating with ActionScript, 7680 organizational chart example, 135139 passwords for access to parts of, 53 planning, 5162 preloaders for, 6, 102, 103, 298306 size of, 119, 120 slide show project, 334337 testing, 128, 284285 unloading, 123, 124125 user-defined components for, 132135
380
Index FI
Flash MX ActionScript For Designers, electronic version on CD-ROM, 360 Flash objects. See objects Flash Player actions for, 30 compatibility for older versions, 26 detecting version of, 345346 Flash movie creation and, 53 Flash slide show project ActionScript to move the image, 336337 customizing for a client, 337 examining code for, 334 example file for, 334 initializing the variables, 335 Flash UI Components book, 26. See also components FlashJester Web site, 367 Flax Web site, 367 flow, controlling for Flash movies, 5354 flyout menu project beginning the project, 204 converting navigation bar to a symbol, 205 converting navigation bar to flyout menu, 205208 overview, 204, 208 flyoutMenu.fla file, 204 _focuserect property, 169 Font user-defined component type, 133 fonts, embedding, 213 for loops, 103, 104106 formatting code, 3839 forms. See Flash forms forward slashes (//) for comments, 3839, 70 Foulds, Andy, 372 Frame command (Insert menu), 67 frame-based loops, 102, 103. See also loops frames. See also keyframes adding, 67 for buttons, 72 converting standard frames to keyframes, 68 copying and pasting, 9899 creating, 6667 deleting, 68 designation on timeline, 66 first frame of movie clips, 82 frame-based loops, 102, 103 goto action for, 77 last frame of movie clips, 83, 86 navigating to random frame, 97, 114117
printable, 310311 types of, 66 uses for, 66 _framesloaded property, 169 FreeHand (Macromedia) on CD-ROM, 360 as planning tool, 56 Frieda, John, 370 function action, 110111, 236, 243 functions calling, 112113, 116117 creating, 110111 generating random frame number, 1416 getting properties of objects, 173174 getting property values, 174 overview, 110 reserved keywords, 4041 for tooltips, 235237 for user-customizable interface, 243245 Functions book, 25
graphics converting to a symbol, 98, 99 nesting bitmaps in movie clips, 100 swapping nested bitmaps, 100, 101102 graphics symbol converting graphics to, 98, 99 interactivity for, 42, 81 overview, 42 green (syntax coloring), 39 GrooveMaker Web site, 366
H
_height property, 169
G
getDate method of Date object, 246 getDay method of Date object, 246 getFullYear method of Date
object, 246
getHours method of Date object, 247 getMinutes method of Date
object, 247
getMonth method of Date object, 246 getProperty function
getting properties for objects, 173174 getting property values, 174 getRGB method of Color object, 175 getSeconds method of Date object, 248 getTransform method of Color object, 175 getURL action opening URL in different size window, 7980 parameters, 78 for pop-up window, 339, 340 for Skip Intro button, 347, 348 using, 7779 Go To command (View menu), 191 goto action adding to script, 47, 77 for frame-based loops, 103 parameters, 77 for returning movie clips to first frame, 83, 86 using, 77
324, 325 hiding and showing. See also displaying mouse cursor, 324325 tooltips, 236237 windows, 240 your designs or techniques, 138 hierarchy of actions, rearranging, 31 hints for code, 40 Hit button state, 74 HTML. See also integrating Flash with HTML ActionScript versus, 52 centering Flash objects on HTML page, 349 CGI script for HTML mail forwarding, 308309 Flash forms versus HTML forms, 297, 306 JavaScript to open Flash file in sized window, 341 JavaScript to open link in another window, 340 tags for rich formatted text, 213, 214 hyperlinks creating a text hyperlink, 223224 creating an e-mail link, 216217
I
identifiers in ActionScript code, 3839 if action. See also conditional statements adding to script, 4647 for animated button label, 202 in conditional statements with multiple outcomes, 157 creating conditional statements using, 156 for detecting Flash Player version, 344, 345
Index IL
381
for Flash slide show project, 336337 in interactive animation project, 184, 185, 186187 for Key objects, 181182 in moving navigation bar project, 253254 for On When Pressed button, 195196 in scrolling text box project, 219220, 222, 223 images. See graphics; movie clips Import command (File menu), 58, 84, 259 Import dialog box, 259 Import from File command (Options menu), 41 Import Video dialog box, 8485 Import Video Settings dialog box, 8586 importing. See also loading audio for video files, 85 items to Assets folder, 5859 scripts, 4142 video files into movie clips, 8486 Index book, finding actions using, 4, 26 input text boxes creating, 210211 options, 210211 setting character options, 212213 Insert a Target Path button (Actions panel), 130 Insert menu. See also New Symbol command (Insert menu) Blank Keyframe command, 68 Clear Keyframe command, 68 Convert to Symbol command, 98, 205, 232, 252, 280 Frame command, 67 Keyframe command, 68 Layer command, 70 Remove Frames command, 68 Scene command, 190 Insert Target Path dialog box, 48, 90, 128 installing items from CD on Macintosh computers, 358 troubleshooting, 360361 on Windows computers, 358 integrating Flash with HTML animated Flash banner project, 352354 banner ads, 341344 detecting the Flash Player version, 345346 Flash introduction, 346348
integrating Flash with Dreamweaver, 348351 pop-up window with JavaScript, 339341 interactive interfaces displaying date and time, 245249 drag-and-drop elements, 238240 moving navigation bar project, 251255 ScrollBar component for, 249250 tooltips, 231238 user-customizable interface, 241245 interactivity. See also interactive interfaces; navigating buttons for, 9596 for graphics symbol, 42, 81 interactive animation project, 183187 movie clips for, 8283 interface.fla file, 241 introduction movie clip overview, 346347 Skip Intro button, 347348 invisible buttons, 74, 75. See also buttons isdown action, in interactive animation project, 184
converting standard frames to, 68 creating, 68 designation for frames with actions assigned, 69 designation on timeline, 66 labeling, 6869 removing content from, 68 stop action for, 76 ticker text marquee project, 226229 uses for, 66, 67 keywords, reserved, 4041 Killer Sound Web site, 366 KISS acronym for variable names, 147 Kravitz, Lenny, 371
L
labels animating button labels, 200203 for keyframes, 6869 for movie clips, 8687 reserved keywords, 4041 swapping for buttons, 198199 template for navigation bar, 197 Layer command (Insert menu), 70 layers Actions layer, 6970 for buttons, 72, 73 Distribute to Layers command (Modify menu), 234 for movie clips, 83 for section movie template, 122 for tooltips, 234, 235 Lenny Kravitz.com site, 371 levels for movies, 121 Library. See document Library Library command (Window menu), 43 light gray (syntax coloring), 39 line numbers in scripts setting breakpoints using, 290 viewing, 35 Linkage Properties dialog box, 312, 313 linking creating a text hyperlink, 223224 creating an e-mail link, 216217 displaying link in pop-up window, 340 JavaScript to open link in another window, 340 to sounds in document Library, 268269 to video files from movie clips, 85 List Objects command (Debug menu), 287 List user-defined component type, 133 List Variables command (Debug menu), 288
J
Jaguar X Type Web site, 371 JavaScript ActionScript versus, 89 creating a pop-up window with, 339341 to open Flash file in sized window, 341 to open link in another window, 340 for opening URL in different size window, 7980 Jittery.fla file, 199 John Coltrane Web site, 373 John Frieda Web site, 370 Juxt Interactive Web site, 371
K
Key down event, 89 Key object uses for, 180181 using, 181182 Key Press event, 92, 9394 Key up event, 89 Keyframe command (Insert menu), 68 keyframes. See also frames Actions layer for, 6970 assigning actions to, 7, 29, 7071 blank, 66, 68, 83 comments for, 70
382
Index LM
Load event, 88 loading data into movie, 216, 217, 218219 movies into base movie, 123124, 125 movies into target movie clip, 127129 movies to hide your design, 138 soundtracks, 267, 277 text from external sources, 215216 loadMovie action hiding your design and, 138 loading movies into base movie, 123124, 125 loading movies into target movie clip, 127129 for soundtracks, 267 loadVariables action in scrolling text box project, 217, 218219 using, 216 locking a script in the Script window, 32 logical operators, 158159 Logical operators book, 24, 25 loops controlling the flow of a movie, 54 creating ActionScript loops, 103107 creating frame-based loops, 103 do while loops, 103, 106107 execution in single frame required for, 103 frame-based versus ActionScript, 102 for loops, 103, 104106 overview, 24 for preloaders, 304305 for sounds, 260 uses for, 11 while loops, 103, 106
M
Macintosh computers installing items from CD, 358 requirements for CD-ROM, 357358 Macromedia Dreamweaver, 348351, 359 Fireworks, 360 Flash Designer and Developer Center Web site, 363 FreeHand, 56, 360 Showcase Web site, 12, 15, 369 support Web site, 363364 Web site, 12 Madonna Web site, 370
managing movie content, 45 mapping your ActionScript, 5758 marquee, ticker text, 225230 marqueeComponent.fla file, 230 masks converting movie clips to, 6062 creating movie clip for, 322 creating within movie clips, 322324 Math object random method, 107109, 115116, 161 round method, 109110, 115, 161 mathematical operators, 145, 147 menus ActionScript for, 12 context menu of Actions panel, 37 drop-down menus of action groups, 29 flyout menu project, 204208 Milla and Partner Web site, 372 Miscellaneous book. See also evaluate action comment action, 293 overview, 24 trace action, 105, 288289, 290 modem settings for testing movies, 301 Modify menu Convert to Blank Keyframes command, 68 Convert to Keyframes command, 68 Distribute to Layers command, 234 Document command, 266 Swap Bitmap command, 102 Swap Symbol command, 101 modular ActionScript for interfaces, 13 uses for, 14 using movie clips for, 113 motion trails completing the effect, 327329 motion tween animation for, 327, 328, 330 overview, 326327, 330 motion tween animation for drag-and-drop elements, 238 for motion trails, 327, 328, 330 mouse chasers basic, 315318 Flash MX object for, 318321 random color for, 319 mouse cursor custom, 325326 showing and hiding, 324325 Mouse down event, 89
mouse events. See also events available events, 92 for button symbol, 42 defined, 9 Key Press, 9394 multiple events for buttons, 9293 on action for, 94 overview, 9293 Release, 75 rollOut, 93 rollOver, 93 Mouse move event, 89 Mouse object custom cursor using, 325326 hide method, 324, 325 overview, 324 show method, 324, 325 Mouse up event, 89 mouseChaserBegin.fla file, 316 .mov files, 84 Move the Selected Actions Down button (Actions panel), 31 Move the Selected Actions Up button (Actions panel), 31 moveTo Drawing method, 321 Movie Clip Control book onClipEvent action, 87, 88, 89 overview, 2324 setProperty action, 170 startDrag action, 238, 239, 240 movie clips. See also Flash movies; target movie clip ActionScript options for, 78 animated clips, creating, 200 assigning actions to objects, 8791 assigning event handler to, 89 button to change size and opacity, 4449 buttons for interactivity, 9596 buttons for navigation, 95 clip events, 9, 8789 cloning, 87 for closing a window, 240 communicating between timelines, 129130 converting timeline animation to, 9899 converting to a mask, 6062 creating new clips, 82 custom cursor using, 325326 detecting the Flash Player version, 345346 down arrow, 219221 for drag-and-drop windows, 239240 duplicating with
duplicateMovieClip
action, 182183
Index MO
383
as effects modules, 113 empty, creating, 320 first frame, 82 importing video files, 8486 instances, creating, 86 for interactivity, 8283 introduction clip, creating, 346348 labeling, 8687 last frame, 83, 86 layers for, 83 loading movies into target clip, 127129 for mask, 322 mask within, creating, 322324 mouse chasers using, 315321 naming, 45 navigating to random frame, 97 nesting symbols in, 74, 97, 99100 On When Pressed button with, 195196 overview, 43, 8182 preloaders for, 6, 102, 103, 298306 returning to first frame, 83, 86 for sound controller project, 277280 for starburst backdrop, 330333 stop action, 46, 76, 82 symbol, 43 target clips, creating, 125127 target path for, 48, 8991 testing, 49 ticker text marquee project, 225230 with action for target path, 8991 Movie Control book goto action, 47, 77, 83, 86, 103 on action, 94, 238 overview, 22 play action, 76 stop action, 46, 76, 82 Movie Explorer, debugging ActionScripts using, 293, 294 movies. See Flash movies; movie clips moving around. See navigating moving navigation bar project, 251255 moving objects actions, changing order of, 31 aligning navigation bar buttons, 199 code in expert mode, 36 positioning target movie clip, 126 positioning tooltips, 233234 scenes, changing order of, 192 movingNavBar.fla file, 251
MP3 compression for soundtracks, 258, 263264 .mpg or .mpeg files, 84 multimedia, ActionScript uses for, 7
N
_name property, 169
named anchors, 189, 193194 names. See also labels for movie clips, 45 for scenes, 190 for section movies, 123 for tooltips, 234 for variables, 147148 navigating. See also interactive interfaces buttons for, 95 getURL action for, 7779 goto action for, 77 moving navigation bar project, 251255 named anchors for, 189, 193194 navigation bar for, 196199 On When Press button for, 194196 play action for, 76 to random frame, 97, 114117 to scenes, 189192 to scripts in Script window, 3132 stop action for, 76 navigation bar building, 199 button template for, 197199 converting to flyout menu, 205208 label template for, 197 moving navigation bar project, 251255 suiting document to, 196 uses for, 196 vertical, 255 wider than movie, 254 nesting symbols animated movie clip in button symbol, 203204 bitmaps in movie clips, 100 child versus parent movie clips, 131 defined, 97 invisible buttons within another symbol, 74 mouse chaser using movie clip, 315318 in movie clips, 74, 97, 99100 overview, 97, 99100 swapping nested symbols, 101 New Document dialog box, 343, 344 New from Template command (File menu), 343
New Symbol command (Insert menu) for button templates, 197 for buttons, 72, 74, 194, 203 for label templates, 197 for movie clips, 82, 99, 200, 311, 323, 327 for target movie clip, 125 newArray method, 153, 154 n.fuse.gfx Web site, 370 normal mode described, 28 switching to expert mode, 35 NOT operator, 158159 <not set yet> warning, 47, 90 Number user-defined component type, 133 numbers in variable names, 148 numeric data variables combining contents of, 144 defined, 142 numeric literal data variables combining contents of, 144 defined, 142 string literals versus numeric literals, 143
O
Object user-defined component type, 132 object-oriented scripting, 78 objects. See also properties; specific objects assigning actions to, 29, 8791 centering on HTML page, 349 displaying list of movie objects with Debugger, 287 duplicating with
duplicateMovieClip
action, 182183 events for actions, 8889 Flash objects and variable names, 147 getting properties, 172173 getting property value, 174 methods in, 2526 overview, 78, 2526 passing variable value to, 150151 placing invisible buttons behind, 74, 75 properties of, 169 setting properties, 108, 168172 tracking using trace action, 289 on (Release) event handler for closing a window, 240 as default for buttons, 42, 91 for drag-and-drop window, 239 for hiding a window, 240 overview, 75 for single action, 49
384
Index OP
on action
for tooltips, 238 using, 94 On When Pressed button creating, 194195 programming movie clip for, 195196 uses for, 194 onClipEvent action, 87, 88, 89 online merchants, ActionScript uses for, 14 onSoundComplete event, 273274 opacity. See _alpha property Open as Library command (File menu), 59, 113, 134 Open dialog box, 41 opening action books, 22, 23 Actions panel, 27 Bandwidth Profiler, 299 context menu of Actions panel, 37 Debugger, 286 document Library, 59 Reference panel, 34 Scene panel, 190 URLs with getURL action, 7780 operators arithmetic, 145, 147 logical, 158159 post-increment form of operand, 146 precedence for expressions, 146 pre-increment syntax of operand, 145 Operators book Arithmetic Operators book, 24 Comparison Operators book, 2425 Logical operators book, 24, 25 Options menu Export as File command, 41 Find command, 33 Import from File command, 41 overview, 3536 Preferences command, 39 OR operator, 158159 order changing for actions, 31 changing for scenes, 192 precedence of operators for expressions, 146 organizational chart project beginning the design, 136137 creating, 135139 creating the ActionScript, 137139 described, 135 Orgchart folder on CD-ROM, 136 orgChart.fla file, 136
P
Panel Sets, adding panel layout to, 28 Panel Sets command (Window menu), 27 panels. See also Actions panel Designer panel layout, 27 docking, 28 Reference panel, 4, 17, 3335 saving layout for, 28 Scene panel, 190 panning a sound, 273 parameter text boxes, using, 30 parent movie clips, 131 parentheses for parameters in code, 38, 39 passing variable value to other objects, 150151 passwords Boolean expression for evaluating, 53, 159 input text box option, 211 for limiting access to parts of movies, 53 for sites, 53 Paste Frames command (Edit menu), 99 Paste in Place command (Edit menu), 252 path, target. See target path Pepworks.com site, 370 Pickled the Movie Web site, 370 pictures. See graphics; movie clips Pin Current Script button (Actions panel), 32 pinning a script, 32 plain English for planning, 57 planning your ActionScript movie controlling the flow, 5354 drafting your design, 56 evolution of an ActionScript, 5254 example project, 6062 extensions, 59 fleshing out your idea, 5859 gathering assets, 5859 importance of, 51 mapping your ActionScript, 5758 planning your design, 5558 research, 55 size of movies, 120 storyboards, 56, 57, 126 play action, 76 PLUGINSPAGE line, 349 pop-up window, creating with JavaScript, 339341
positioning. See also moving objects; order aligning navigation bar buttons, 199 target movie clip, 126 tooltips, 233234 Pray Station Web site, 372 precedence of operators for expressions, 146 Preferences command (Options menu), 39 preferences for syntax coloring, 39 preloaders ActionScript for preload loop, 304305 ActionScript for recycling the loop, 305 analyzing movies for bandwidth problems, 299302 animated, 298306 conditional statement for, 305, 306 creating, 302306 defined, 298, 302 displaying number of bytes loaded, 306 frame-based loops in, 102, 103 need for, 298 progress bar for, 303 visual effects for, 6 Press event, 92 previewing. See also testing designs in Flash environment, 284 designs in Web browsers, 285 sounds, 264, 265 printable frames, 310311 Printing book, 24 ProFlasher Web site, 365 progress bar for preloader, 303 projects animated Flash banner, 352354 drawing outside the lines, 6062 e-commerce catalog, 312313 first ActionScript, 4449 Flash slide show, 334337 flyout menu, 204208 generating random quotes, 160164 interactive animation, 183187 moving navigation bar, 251255 navigating to random frame, 114117 organizational chart, 135139 scrolling text box, 217223 sound controller, 274281 ticker text marquee, 225230
Index PS
385
properties. See also Property inspector; setting properties available properties, 169 changing by a given value, 172 experimenting with, 62 getting for objects, 172173 getting value of, 174 overview, 25 setting, 46, 108, 168172 Properties book _alpha property, 48 available properties, 169 overview, 25 _xscale property, 49 _yscale property, 49 Property inspector for character options, 212213 for custom cursor, 325 for dynamic text boxes, 211212 for input text boxes, 210211 for keyframe labels, 69 for movie clip labels, 8687 in moving navigation bar project, 253 for named anchors, 193 for printable frames, 311 for rich formatted text, 213215 Swap button, 101, 102 for text hyperlinks, 223224 Protect from Import option, 138 Publish Settings command (File menu), 193, 266 Publish Settings dialog box, 193194 punctuation, variable names and, 147
Q
_quality property, 169
QuickTime linking from movie clips to external files, 85 sound files supported by, 258 video files supported by, 84 quotation marks () for string literal data, 143
R
random frames, navigating to, 97, 114117 random numbers creating a variable with value equal to, 108109 generating with random method of Math object, 107109, 161 navigating to random frame, 114117 in random quote generation project, 160164
rounding random values, 109110, 161 setting highest number for, 109 uses for, 107, 108 Random quote project adding a time and accessing the array, 161163 beginning the project, 160 finishing the project, 163164 generating the random number, 161 randomStars.fla file, 331 ReadMe.txt file, 361 red flag for labeled keyframes, 69 for warnings, 40, 47, 89 Reference panel, 4, 17, 3335 registration point for symbols, 205, 206 relative mode for target path, 130, 131 Release event, 75, 92. See also on (Release) event handler Release Outside event, 92 Remove Frames command (Insert menu), 68 removing. See deleting Replace dialog box, 33 replacing text in a script, 33 research, 55 reserved keywords list of, 4041 variable names and, 147 Reset button for Flash forms, 308 rich formatted text creating, 213215 HTML tags for, 214 rndFrame function calling, 112113 creating, 114116 using with a button, 116117 rndQuote.fla file, 160 Rob Allen Photography Web site, 370 rollOut event, 92, 93, 238 rollOver event, 92, 93, 238 rotation, changing direction of, 202 _rotation property, 169 rounding random values, 109110, 115, 161
S
Save As command (File menu), 123 Save As dialog box, exporting scripts, 41 Save Panel Layout command (Window menu), 28 saving breakpoints, 291 Scene command Insert menu, 190 Window menu, 190, 191, 192
Scene panel, opening, 190 scenes. See also preloaders; segments adding to a movie, 190 deleting, 191192 duplicating, 192 naming, 190 navigating to, 191 opening Scene panel, 190 for preloaders, 303 rearranging order of, 192 uses for, 189190 Script pane. See also scripts described, 21, 32 expert mode and, 36 loading text from external sources, 215216 Script window of Actions panel navigating to scripts with, 3132 pinning a script, 32 scripts. See also code; debugging; specific actions adding actions to, 29 for animating button labels, 200203 creating in expert mode, 36 debugging, 283294 deleting actions from, 31 experimenting with, 62 exporting, 41 finding and replacing text in, 33 finding text in, 33 importing, 4142 modular, using movie clips for, 113 navigating to, with Script window, 3132 pinning, 32 programming a button to change size and opacity of image, 4449 viewing line numbers in, 35 ScrollBar component, 249250 scrolling text box project beginning the project, 217218 End of Page button, 221 loading the text document into the movie, 218219 programming the down arrow, 219221 slider code, 221222 up arrow, 223 scrollText.fla file, 217 scrollText.txt files, 217 scrollTick.fla file, 225 searching. See finding sections of movies. See scenes; segments
386
Index S
security, hiding your designs or techniques, 138 segments. See also scenes base movie for, 120, 121 dimensions of, 121, 125 labels for, 190 naming, 123 planning, 120 template for, 121123 uses for, 119120 semi-colon (;) as end of line identifier, 38, 39 set variable action accessing arrays using, 162 adding to script, 48 for Color objects, 175 for color transformation objects, 178 creating variable equal to random number, 108109, 114116 for Date objects, 245 for detecting Flash Player version, 345 resetting a variable, 308 setBGcolor function, 243245 setMask method, 324 setPan method of Sound object, 273 setProperty action, adding to script, 170 setRGB method of Color object described, 175 for user-customizable interface, 244 using, 176 setting properties by addressing target path, 171172 directly, 168170 initial state, 46 to random value, 108 setProperty action for, 170 with action for, 168170 setTransform method of Color object described, 175176 offset values for, 177 parameters, 176177 percentage values for, 177 tinting a multi-colored object using, 178180 setVariable action creating arrays, 153 creating variables, 148149 setVolume method of Sound object, 272273 shareware programs, 359 show method of Mouse object, 324, 325 Show Streaming command (View menu), 302
showing. See displaying; hiding and showing Simian Volume 6 Revolt Web site, 372 simpleChaserBegin.fla file, 318 Skip Intro button, 260, 347348 slide show. See Flash slide show project Slider Control symbol, 275276 sliders for scrolling, 221222 for sound controller project, 275276, 278279 slideShow.fla file, 334 Sonic Foundry.com site, 366 Sorenson Web site, 368 sound controller project adding buttons and sliders, 275277 beginning the project, 275 evaluating slider position, 279 initial values for sliders, 278279 overview, 274 programming the movie clip, 277280 Sound Designer II format, 258 sound file formats, 258 Sound object attaching a sound, 269270, 276, 277 changing volume for sound, 272273 creating an instance, 268 in document Library, attaching, 269270 in document Library, linkage for, 268269 panning a sound, 273 sound controller project, 274281 starting a sound, 270271 stopping a sound, 271272 triggering an event at sound completion, 273274 uses for, 6, 268 Sound only QuickTime Movie format, 258 Sound Properties dialog box, 263264, 265 Sound Shopper.com site, 367 Sound Strike Web site, 367 _soundbuftime property, 169 Soundcontroller folder on CD-ROM, 274 soundtracks adding to timeline, 257258 attaching, 269270, 276, 277 custom effects, 260262 effects, 259 export settings, 263265 file formats supported, 258
importing for video files, 85 importing sounds, 258260 loading into your design, 267, 277 MP3 compression for, 258, 263264 in separate movie, 258, 266267 size of file for, 258 sound controller project, 274281 Speech compression for, 264265 streaming sound, 260 Web sites, 366367 spaces, variable names and, 148 Speech compression for soundtracks, 264265 starburst backdrop creating the stars, 332333 example file for, 331 initializing the movie clip, 332 modifying the movie, 333 overview, 330331 start method of Sound object, 270271 startDrag action, 238, 239, 240 sticky notes, for planning your ActionScript, 58 stop action, 46, 76, 82 stop method of Sound object, 271272 storyboards creating, 56, 57 usefulness of, 126 Streaming Graph command (View menu), 299 streaming sound, 260 string data variables, 142, 143 String user-defined component type, 133 strings, 25. See also text submarine animation project, 183187 submarine.fla file, 183 Submit button for Flash forms CGI script for HTML mail forwarding, 308309 programming the button, 309310 Sun AU sound format, 258 Swap Bitmap command (Modify menu), 102 Swap Bitmap dialog box, 102 Swap Symbol command (Modify menu), 101 Swap Symbol dialog box, 101 swapping nested bitmaps, 100, 101102 SWF (Small Web File) exporting from FreeHand, 56 size of, 4, 119 SWfx (WildForm), on CD-ROM, 360 Swift 3D, on CD-ROM, 360
Index SU
387
Swish Web site, 368 symbols. See also converting; Create New Symbol dialog box; nesting symbols; specific types in document Library, 4344 registration point for, 205, 206 types of, 4243 syntax coloring, 37, 39 syntax of actions, finding in Reference panel, 4 System 7 Sounds format, 258 system requirements for CD-ROM, 357358
T
target movie clip aligning for proper loading, 126 communicating between timelines, 129130 creating, 125127 loading movies into, 127129 for organizational chart, 136, 137 positioning, 126 target path absolute mode, 130, 131 alias, 132 defined, 9 overview, 910 relative mode, 130, 131 setting properties by addressing, 171172 specifying for movie clips, 48, 8991, 128 Target Path dialog box, 131 _target property, 169 technical support for CD-ROM, 361 templates for banner ads, 343, 344 button templates, 197198 for documents with named anchors, 193194 label template for navigation bar, 197 for section movies, 121123 Test Movie command (Control menu), 49, 163 testing after completing milestones, 128 analyzing movies for bandwidth problems, 299302 designs in Flash environment, 284 designs in Web browsers, 285 modem settings for testing movies, 301 movie clips, 49, 163 sounds, 264, 265
text. See also dynamic text boxes creating data in word processor, 216 dynamic text boxes, creating, 211212 e-mail links, creating, 216217 finding and replacing in a script, 33 finding in a script, 33 hyperlinks, 223224 hyperlinks, creating, 223224 input text boxes, creating, 210211 loading from external sources, 215216 populating dynamic text boxes with array elements, 224225 rich formatted text, creating, 213215 scrolling text box project, 217223 setting character options, 212213 ticker text marquee project, 225230 text boxes. See dynamic text boxes; input text boxes text data variables. See string data variables text objects, 25. See also text TextField object, 6 Thrash, Dox, 371 ticker text marquee project, 225230 time displaying current time, 247249 retrieving from host computer, 248 timelines adding comments to keyframes, 70 assigning actions to keyframes, 7071 communicating between, 129130 controlling, 6670 converting animation to movie clip, 9899 creating Actions layer for, 6970 creating buttons, 7275 navigating with ActionScript, 7680 need for, 65 overview, 9 soundtrack in, 257258 typical timeline, 67 working with frames, 6669 timer component, 162, 203
tooltips creating, 232233 creating functions for, 235237 example file on CD-ROM, 238 layers for, 234, 235 naming, 234 positioning, 233234 programming buttons for, 237238 showing and hiding, 236237 uses for, 231232 toolTips.fla file, 238 Toon Boom Studio Web site, 368 _totalFrames property, 169 trace action breakpoints with, 290 for loops with, 105 tracking variables or objects using, 289 uses for, 288289 trial versions of programs, 359 troubleshooting the CD-ROM, 360361 TurtleShell.com site, 365 Tweened.com site, 372
U
UI components. See components Undo command (Edit menu), 42 undoing, 42 Unload event, 89 unloading movies, 123, 124125, 267 unloadMovie action, 123, 124125, 267 up arrow for scrolling, 223 Up button state, 73 Up constant, 184 _url property, 169 URLs. See also Web sites creating a text hyperlink, 223224 creating an e-mail link, 216217 getURL action, 7780, 339, 340, 347, 348 for loadVariables action, 216 researching competitor URLs, 55 User Defined Functions book call function action, 112113, 116, 237, 243 function action, 110111, 236, 243 overview, 24 rndFrame action, 114117 user-customizable interface creating, 241 creating the function for, 243245 programming the buttons, 242243
388
Index UY
user-defined components creating instances of, 134 creating new components, 132134 defined, 132 downloading, 135 storing in document Library, 134135 types of, 132133 using, 134135
V
var action, 149 The variable name you have entered... message,
40, 148 variables arrays versus, 151152 Boolean data, 142 combining array elements in, 152 combining contents of, 143144, 150 comparing multiple values to an array, 151152 declaring, 148150 displaying list using Debugger, 288 expressions in, 144146 local, creating, 149150 naming, 147148 numeric data, 142 numeric literal data, 142 passing value to other objects, 150151 reserved keywords and commands, 4041, 147 resetting, 308 setting value equal to two other variables, 151 string data, 142, 143144 tracking using trace action, 289 types of, 142 uses for, 5, 141 with value equal to random number, 108109, 114 watching with Debugger, 286287 Variables book. See also set variable action overview, 24 setVariable action, 148149, 153 var action, 149 with action, 8991, 129130, 168
Velocity Studio Web site, 371 vertical navigation bar, 255 video files embedding, 84, 85 importing into movie clips, 8486 linking from movie clips, 85 types of, 84 View menu Bandwidth Profiler command, 299 Go To command, 191 Show Streaming command, 302 Streaming Graph command, 299 viewing. See displaying; hiding and showing Virtual FX Web site, 365 _visible property, 169 visual effects, for preloaders, 6 visual mind map, 58 volume for sound, changing, 272273
W
warnings. See error messages and warnings WAV sound format, 258 Web browsers JavaScript to open link in another window, 340 previewing designs in, 285 Web Monkey Web site, 365 Web site designers orientation of, 3 uses for ActionScript, 47 Web site elements animated preloader, 298306 e-commerce catalog project, 312313 Flash forms, 206210 printable frames, 310311 Web sites for extensions, 59, 135 Flash Deployment Kit, 346 Flash resources, 363366 Flash tutorial sites, 59 for inspiration, 369373 Macromedia, 12 Macromedia Showcase, 12, 15, 369 researching, 55 for sounds and music, 366367 for third-party applications, 367368 for user-defined components, 135
Were Here Forums Web site, 366 while loops, 103, 106 _width property, 169 WildForm SWfx on CD-ROM, 360 Web site, 368 Wiley Publishing Customer Care, 361 Wiley Publishing Customer Service, 361 Window menu Actions command, 27 Common Libraries command, 113 Library command, 43 Panel Sets command, 27 Save Panel Layout command, 28 Scene command, 190, 191, 192 windows creating a pop-up window with JavaScript, 339341 drag-and-drop, 239240 JavaScript to open Flash file in sized window, 341 JavaScript to open link in another window, 340 movie clip for closing, 240 Windows computers installing items from CD, 358 requirements for CD-ROM, 357 with action for changing object properties, 168 for communicating between timelines, 129130 for target path of movie clips, 8991 .wmv files, 84 word processor creating array data in, 154, 160 creating text data in, 216
X
_x property, 169 _xmouse property, 169 _xscale property, 49, 169
Y
_y property, 169 _ymouse property, 169 _yscale property, 49, 169
5. Limited Warranty. (a) WPI warrants that the Software and Software Media are free from defects in materials and workmanship under normal use for a period of sixty (60) days from the date of purchase of this Book. If WPI receives notification within the warranty period of defects in materials or workmanship, WPI will replace the defective Software Media. (b) WPI AND THE AUTHOR OF THE BOOK DISCLAIM ALL OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE SOFTWARE, THE PROGRAMS, THE SOURCE CODE CONTAINED THEREIN, AND/OR THE TECHNIQUES DESCRIBED IN THIS BOOK. WPI DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE SOFTWARE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFTWARE WILL BE ERROR FREE. (c) This limited warranty gives you specific legal rights, and you may have other rights that vary from jurisdiction to jurisdiction. 6. Remedies. (a) WPIs entire liability and your exclusive remedy for defects in materials and workmanship shall be limited to replacement of the Software Media, which may be returned to WPI with a copy of your receipt at the following address: Software Media Fulfillment Department, Attn.: Flash MX ActionScript For Designers, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, or call 1-800-762-2974. Please allow four to six weeks for delivery. This Limited Warranty is void if failure of the Software Media has resulted from accident, abuse, or misapplication. Any replacement Software Media will be warranted for the remainder of the original warranty period or thirty (30) days, whichever is longer. (b) In no event shall WPI or the author be liable for any damages whatsoever (including without limitation damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising from the use of or inability to use the Book or the Software, even if WPI has been advised of the possibility of such damages. (c) Because some jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation or exclusion may not apply to you. 7. U.S. Government Restricted Rights. Use, duplication, or disclosure of the Software for or on behalf of the United States of America, its agencies and/or instrumentalities (the U.S. Government) is subject to restrictions as stated in paragraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause of DFARS 252.227-7013, or subparagraphs (c) (1) and (2) of the Commercial Computer Software - Restricted Rights clause at FAR 52.227-19, and in similar clauses in the NASA FAR supplement, as applicable. 8. General. This Agreement constitutes the entire understanding of the parties and revokes and supersedes all prior agreements, oral or written, between them and may not be modified or amended except in a writing signed by both parties hereto that specifically refers to this Agreement. This Agreement shall take precedence over any other documents that may be in conflict herewith. If any one or more provisions contained in this Agreement are held by any court or tribunal to be invalid, illegal, or otherwise unenforceable, each and every other provision shall remain in full force and effect.