MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual
MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual

Learning actionscript 2.0 in flash
Table of Contents

Advertisement

Learning ActionScript 2.0 in Flash

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

Summary of Contents for MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH

  • Page 1 Learning ActionScript 2.0 in Flash...
  • Page 2 If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
  • Page 3: Table Of Contents

    Contents Introduction ..........9 Intended audience .
  • Page 4 Chapter 5: Syntax and Language Fundamentals ... . 113 About syntax, statements, and expressions ..... .114 About dot syntax and target paths.
  • Page 5 Chapter 10: Handling Events ......329 Using event handler methods ....... . . 330 Using event listeners .
  • Page 6 Chapter 13: Animation, Filters, and Drawings....469 Scripting animation with ActionScript 2.0 ..... .470 About bitmap caching, scrolling, and performance .
  • Page 7 Chapter 18: Debugging Applications ..... . 711 Debugging your scripts ........711 Using the Output panel .
  • Page 8 Contents...
  • Page 9: Introduction

    Introduction Macromedia Flash Basic 8 and Macromedia Flash Professional 8 are the professional standard authoring tools for producing high-impact web experiences. ActionScript is the language you use to add interactivity to Flash applications, whether your applications are simple animated SWF files or more complex rich Internet applications. You don’t have to use ActionScript to...
  • Page 10: System Requirements

    787. Updating Flash XML files It is important that you always have the latest Flash XML files installed. Macromedia sometimes introduces features in dot releases (minor releases) of Flash Player. When such a release is available, you should update your version of Flash to get the latest XML files.
  • Page 11 Learning ActionScript 2.0 book overview The following list summarizes the contents of this manual: Chapter 1, “What’s New in Flash 8 ActionScript,” describes features that are new in ActionScript, changes to the compiler and debugger, and the new programming model for the ActionScript 2.0 language.
  • Page 12 Chapter 15, “Working with Images, Sound, and Video,” describes how to import external media files, such as bitmap images, MP3 files, Flash Video (FLV) files, and other SWF files, in your Flash applications. This chapter also provides an overview of how to work with video in your applications, and how to create progress bar loading animations.
  • Page 13 , typically within a procedure, indicates code that you need to modify or Bold code font add to code you have already added to your FLA file. In some case, it might be used to highlight code to look at. Boldface text indicates data you need to type into the user interface, such as a filename or instance name.
  • Page 14: Additional Resources

    In addition to this manual about ActionScript, there are manuals on other Flash topics, such as components and Macromedia Flash Lite. You can access each manual in the Help panel (Help > Flash Help), by viewing the default Table of Contents. Click the Clear button to see each manual that’s available;...
  • Page 15 In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\ Samples and Tutorials\Samples\ActionScript\. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/ Samples and Tutorials/Samples/ActionScript/. You might find the following components-focused sample files useful, because they contain a lot of ActionScript code. They’re also in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\ Samples and Tutorials\Samples\Components\.
  • Page 16 Please read these guidelines closely, or your comment might be removed from the website. If you have a question about Flash, please ask it on the Macromedia web forums: www.macromedia.com/support/forums/. The web forums are the best place to ask questions, because there are many Macromedia employees, Team Macromedia volunteers, Macromedia user group managers and members, and even technical writers who monitor these forums.
  • Page 17 Flash, your applications, or the ActionScript language. The forums are monitored by Team Macromedia volunteers and often visited by Macromedia employees as well. If you’re not sure where to go, or how to solve a problem, a Flash forum is a good place to start.
  • Page 18 Introduction...
  • Page 19: Chapter 1: What's New In Flash 8 Actionscript

    What’s New in Flash 8 ActionScript Macromedia Flash Basic 8 and Macromedia Flash Professional 8 provide several enhancements that make it easy for you to write robust scripts using the ActionScript (AS) language. The new features, which are discussed in this chapter, include new language elements (see “Additions to the ActionScript language”...
  • Page 20 The following features were added to both Flash Basic 8 and Flash Professional 8 (unless noted otherwise): ActionScript editor enhancements let you show hidden characters in your scripts. For more information, see “Showing hidden characters” on page Debug options are now available in the Script window, as well as the Actions panel, for ActionScript files.
  • Page 21 A new garbage collector is built into Flash Player, which uses an incremental collector to improve performance. The workflow for creating accessible applications is improved. Flash Player 8 no longer requires developers to add all objects to the tab index for content to be read correctly by a screen reader.
  • Page 22 Additions to the ActionScript language This section lists additions to ActionScript language elements and classes that are new or changed in Flash 8. The following classes and language elements are new additions or newly supported in Flash Player 8. The following classes were added to ActionScript 2.0 in Flash 8: The BevelFilter class (in flash.filters package) lets you add bevel effects to objects.
  • Page 23 The Locale class (in the mx.lang package) lets you control how multilanguage text appears in a SWF file. The Matrix class (in the flash.geom package) represents a transformation matrix that determines how to map points from one coordinate space to another. The Point class (in the flash.geom package) represents a location in a two-dimensional coordinate system (x represents the horizontal axis, and y represents the vertical axis).
  • Page 24 event handler of the LoadVars class returns the status code that’s onHTTPStatus returned from the server (for example, the value 404 for page not found). For more information, see in the onHTTPStatus (LoadVars.onHTTPStatus handler) ActionScript 2.0 Language Reference. method of the MovieClip class, which attaches a bitmap image to a attachBitmap() movie clip.
  • Page 25 parameter of the event handler returns status MovieClipLoader onLoadComplete the status code that’s returned from the server (for example, the value 404 for page not found). For more information, see onLoadComplete in the ActionScript 2.0 (MovieClipLoader.onLoadComplete event listener) Language Reference. event handler of the MovieClipLoader class is invoked when a file onLoadError loaded with...
  • Page 26 property in the TextFormat class, which lets you specify the amount letterSpacing of space that is uniformly distributed between characters. property in the Video class, which is the specified amount of transparency for _alpha the video object. property in the Video class, which indicates the height of the video instance. _height property in the Video class, which indicates the instance name of the video.
  • Page 27 property of the XMLNode class, which reads the prefix of the node name. prefix method of the XMLNode class, which returns the getNamespaceForPrefix() namespace URI associated with the specified prefix for the node. method of the XMLNode class, which returns the prefix getPrefixForNamespace associated with a specified namespace URI for the node.
  • Page 28: Changes To Security Model For Locally Installed Swf Files

    Reload modified files You can reload modified script files when working on an application. A warning message appears, prompting you to reload the modified script files associated with the application you’re working on. This feature is particularly beneficial to teams working on applications at the same time, in that it helps you avoid working with outdated scripts, or overwriting newer versions of a script.
  • Page 29 In Flash Player 7 and earlier, local SWF files had permissions to access both the local file system and the network. In Flash Player 8, local SWF files can have three levels of permission: Access the local file system only (the default level). The local SWF file can read from the local file system and universal naming convention (UNC) network paths and cannot communicate with the Internet.
  • Page 30 What’s New in Flash 8 ActionScript...
  • Page 31: Chapter 2: Writing And Editing Actionscript 2.0

    Writing and Editing ActionScript 2.0 When you write ActionScript code in Macromedia Flash Basic 8 or Macromedia Flash Professional 8, you use the Actions panel or Script window. The Actions panel and Script window contain a full-featured code editor (called the ActionScript editor) that includes code hinting and coloring, code formatting, syntax highlighting, syntax checking, debugging, line numbers, word wrapping, and support for Unicode in two different views.
  • Page 32: About Actionscript And Events

    About ActionScript publish settings......... 62 About ActionScript and events In Macromedia Flash Basic 8 and Macromedia Flash Professional 8, ActionScript code is executed when an event occurs: for example, when a movie clip is loaded, when a keyframe on the timeline is entered, or when the user clicks a button.
  • Page 33: Organizing Actionscript Code

    Clip events Within a movie clip, you may react to a number of clip events that are triggered when the user enters or exits the scene or interacts with the scene by using the mouse or keyboard. You might, for example, load an external SWF file or JPG image into the movie clip when the user enters the scene, or allow the user’s mouse movements to reposition elements in the scene.
  • Page 34 Rather than attaching your scripts to elements like keyframes, movie clips, and buttons, you should respond to events by calling functions that reside in a central location. One method is to attach embedded ActionScript to the first or second frame of a timeline whenever possible so you don’t have to search through the FLA file to find all your code.
  • Page 35: Using The Actions Panel And Script Window

    However, Macromedia recommends that you do not add scripts directly to these elements (keyframes and objects). Instead, you should respond to events by calling functions that reside in a central location, as described in “Organizing ActionScript...
  • Page 36: About The Actions Panel

    About the Actions panel You use the Actions panel to create ActionScript in a Flash document (a FLA file). The Actions panel consists of three panes, each of which supports you in creating and managing scripts. Pop-up menu Actions toolbox Script navigator Script pane Actions toolbox...
  • Page 37: About The Script Window

    Script pane The Script pane is where you type your code. The Script pane provides you with tools to create scripts in a full-featured editor (called the ActionScript editor) that includes code syntax formatting and checking, code hinting, code coloring, debugging, and other features that simplify creating scripts.
  • Page 38: About Coding In The Actions Panel And Script Window

    You will also notice that many of the options available in the Actions panel are unavailable in the Script window. The Script window supports the following editor options: the Actions toolbox, find and replace, syntax checking, automatic formatting, code hinting, and debug options (ActionScript files only).
  • Page 39 The following topics present the many features of the ActionScript editor (Actions panel and Script window): “About the Actions panel and Script window toolbars” on page 39 “About ActionScript editing options” on page 41 “About ActionScript preferences” on page 42 “About code hinting in Flash”...
  • Page 40 The features you find in the toolbar are discussed in detail in “Using the Actions panel and Script window” on page 35. A quick summary of the buttons you find on the toolbars of both the Actions panel and the Script window follows. Some of the following options are found in the Actions panel only.
  • Page 41 Pop-up menu Actions panel only. Contains the many commands and preferences that apply to the Actions panel or Script window. For example, you can set line numbers and word wrapping in the ActionScript editor, access the ActionScript preferences, and import or export scripts.
  • Page 42 Import script Allows you to import a script file (ActionScript) into the Script pane. For more information, see “Import and export preferences” on page Export script Exports the current script to an external ActionScript (AS) file. For more information, see “Import and export preferences”...
  • Page 43 To access ActionScript preferences in the Script window, select Edit > Preferences and then click ActionScript (Windows) or Flash > Preferences and then click ActionScript (Macintosh). The following image shows the ActionScript settings you can change in Flash 8. You can set the following preferences: Automatic indentation When automatic indentation is turned on, the text you type after an opening parenthesis [(] or opening curly brace ({) is automatically indented according to...
  • Page 44 Use dynamic font mapping Checks to ensure that the selected font family has the necessary glyphs to render each character. If not, Flash substitutes a font family that contains the necessary characters. For more information, see “Formatting code” on page Encoding Specifies the character encoding used when opening, saving, importing, and exporting ActionScript files.
  • Page 45 About triggering code hints When you work in the Actions panel or Script window, Flash can detect what action you are entering and display a code hint. The two different styles of code hint are a tooltip that contains the complete syntax for that action, and a pop-up menu that lists possible method or property names (sometimes referred to as a form of code completion).
  • Page 46 To specify a delay for code hints: In the Actions panel or Script window, select Edit > Preferences (Windows) or Flash > Preferences (Macintosh) from the main menu. Click ActionScript in the Category list. Use the slider to select an amount of delay. The amount of delay is in seconds.
  • Page 47 To dismiss the code hint, do one of the following: Type a closing parens [ Click outside the statement. Press Escape. To work with menu-style code hints: Display the code hint by typing a period after the variable or object name. The code hint menu appears.
  • Page 48 Do one of the following: Click Show Code Hint in the Actions panel or Script window toolbar. Press Control+Spacebar (Windows) or Command+Spacebar (Macintosh). If you are working in the Actions panel, select Show Code Hint from the pop-up menu. About typing objects to trigger code hints When you use ActionScript 2.0, you can use strict typing for a variable that is based on a built-in class, such as Button, Array, and so on.
  • Page 49 The following table lists the suffixes required for support of automatic code hinting: Object type Variable suffix Array _array Button _btn Camera _cam Color _color ContextMenu ContextMenuItem _cmi Date _date Error _err LoadVars LocalConnection Microphone _mic MovieClip MovieClipLoader _mcl PrintJob NetConnection NetStream SharedObject...
  • Page 50 // Object theObject; // Array theArray; // MovieClip theMc; However, Macromedia recommends that instead of this technique, you use strict data typing (see “About typing objects to trigger code hints” on page 48) or suffixes (see “About using...
  • Page 51 To format code according to Auto Format settings, do one of the following: Click the Auto Format button in the Actions panel or Script window toolbar. In the Actions panel, select Auto Format from the pop-up menu. Press Control+Shift+F (Windows) or Command+Shift+F (Macintosh). In the Script window, select Tools >...
  • Page 52 To set preferences for syntax coloring as you type, do one of the following: Select Edit > Preferences (Windows) or Flash > Preferences (Macintosh), click ActionScript in the Category list, and specify Syntax coloring settings. In the Actions panel, select Preferences from the pop-up menu (at the upper right of the Actions panel) and specify Syntax coloring settings in ActionScript preferences.
  • Page 53 For example, if you are working in the Script pane and press Escape+d+o, the following code is placed in your script: do { } while (); The insertion point is placed immediately following the word , so you can begin typing while your condition.
  • Page 54 The following symbols are used to display each hidden character: single-byte space double-byte space >> line break To show hidden characters, do one of the following: Select Hidden Characters from the pop-up menu. Press Control+Shift+8 (Windows) or Command+Shift+8 (Macintosh). With hidden characters shown, the Script pane looks like this: Using the Find tool The Find tool allows you to find and optionally replace text string in your scripts.
  • Page 55 Click Find Next. If the text or characters are present in the script, the words or characters will be highlighted in the Script pane. To find and replace text in a script: From the Actions panel or Script window toolbar, click the Find tool or press Control+F (Windows) or Command+F (Macintosh).
  • Page 56 To check for punctuation balance, do one of the following: Click between braces ({}), brackets ([]), or parentheses [()] in your script. For Windows, press Control+' (single quote), or for Macintosh, press Command+' (single quote) to highlight the text between braces, brackets, or parentheses. The highlighting helps you check that opening punctuation has corresponding closing punctuation.
  • Page 57 Unicode support for ActionScript Flash 8 supports Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file. For example, you can include text in English, Japanese, and French in the same file. When you use a non-English application on an English system, the Test Movie command (see “Debugging your scripts”...
  • Page 58: About Actions Panel Features

    To turn the export encoding warning off or on: In the Flash system menu, select Edit > Preferences (Windows) or Flash > Preferences (Macintosh), and click Warnings from the Category list. Select or deselect Warn on encoding conflicts when exporting ActionScript files. About Actions panel features The following features are only available in the Actions panel.
  • Page 59 In the example below, the function was added to the Script pane. Script Assist gotoAndPlay displays all of the prompts needed to use this ActionScript function—in this case, the scene name, the type, and the frame number. Pinning scripts in the Actions panel If you don’t centralize your code within a FLA file in one location (discussed in “Organizing ActionScript code”...
  • Page 60 To pin a script: Position your mouse pointer on the Timeline so the script appears in a tab at the lower left of the Script pane in the Actions panel. Do one of the following: Click the pushpin icon to the right of the tab. Right-click (Windows) or Control-click (Macintosh) on the tab, and select Pin Script.
  • Page 61: About Behaviors

    The Target Path tool, which is available in the Actions panel, prompts you to enter the target path for the selected action in your script. To insert a target path: Select and position the pointer in an action in your script. Click Target Path on the Actions panel toolbar.
  • Page 62: About Actionscript Publish Settings

    The behavior is added to the object and is displayed in the Actions panel. About ActionScript publish settings You can edit ActionScript in two ways. You can edit ActionScript that is embedded into a Flash document by using the Actions panel. Or you can edit ActionScript that is in a separate script file, external to the Flash document, using the Script window.
  • Page 63 To change the ActionScript version: Select File > Publish Settings and then select the Flash tab. Select the ActionScript version from the pop-up menu. ActionScript 2.0 is selected by default. If you write your scripts in ActionScript 1.0 instead of 2.0, change this setting before you publish your Flash document. The ActionScript 2.0 compiler compiles all ActionScript 1.0 code, with the following exception: the slash (/) syntax used to indicate movie clip paths (for example, parentClip/...
  • Page 64 Do one of the following: To add a directory to the classpath, click Browse to Path, browse to the directory you want to add, and click OK. Alternatively, click Add New Path (+) to add a new line to the Classpath list. Double- click the new line, type a relative or absolute path, and click OK.
  • Page 65 Flash Professional 8 or Flash Basic 8. Typical paths to this folder are as follows: Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Classes. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Classes. The Classes folder is organized into folders that contain directories that contain the classes for Flash Player 7 (FP7) and Flash Player 8 (FP8).
  • Page 66 Writing and Editing ActionScript 2.0...
  • Page 67: Chapter 3: About Actionscript

    CHAPTER 3 About ActionScript The object-oriented programming (OOP) features in ActionScript 2.0 are based on the ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see www.mozilla.org/js/language/es4/index.html). Because the ECMA-4 proposal is not yet a standard, and because it is still changing, ActionScript 2.0 is loosely based on this specification.
  • Page 68: What Is Actionscript

    Although Macromedia recommends that you use ActionScript 2.0, you can continue to use ActionScript 1.0 syntax, especially if you are doing more traditional Flash work such as simple animation that doesn’t require user interaction. What is ActionScript The main features of ActionScript 2.0 include the following:...
  • Page 69: About Choosing Between Actionscript 1.0 And Actionscript 2.0

    About choosing between ActionScript 1.0 and ActionScript 2.0 When you start a new document or application in Flash, you must decide how to organize its associated files. You might use classes in some projects, such as when you are building applications or complex FLA files, but not all documents use classes.
  • Page 70: Understanding Actionscript And Flash Player

    Understanding ActionScript and Flash Player If you compile a SWF file that contains ActionScript 2.0 with publish settings set to Flash Player 6 and ActionScript 1.0, your code functions as long as it does not use ActionScript 2.0 classes. No case sensitivity is involved with the code, only Flash Player. Therefore, if you compile your SWF file with Publish Settings set to Flash Player 7 or 8 and ActionScript 1.0, Flash enforces case sensitivity.
  • Page 71: Chapter 4: Data And Data Types

    CHAPTER 4 Data and Data Types This chapter is the first of several chapters that outline and demonstrate some fundamental concepts of ActionScript. You’ll practice some basic coding techniques to learn how to create complex applications. In this chapter, you’ll also learn about how to work with data in a FLA file, and what kinds of data you can work with.
  • Page 72: About Data Types

    Some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), Boolean values ( true ), and so on. In this chapter, you’ll also learn about the data types in Flash and how to false use them.
  • Page 73 You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes.
  • Page 74 You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes.
  • Page 75 Boolean data type A Boolean value is one that is either . ActionScript also converts the values true false when appropriate. Boolean values are most often used with logical true false operators in ActionScript statements that make comparisons to control the flow of a script. The following example loads a text file into a SWF file, and displays a message in the Output panel if the text file does not load correctly, or the parameters if it does load successfully.
  • Page 76 Stage: getURL() my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product); The second example returns the width of a movie clip called on the Stage. The targeted my_mc instance must be a movie clip, and the returned value must be a numeric value.
  • Page 77 The second example creates a movie clip called that uses the Drawing API to draw square_mc a rectangle. Event handlers and the methods of the MovieClip startDrag() stopDrag() class are added to make the rectangle draggable. this.createEmptyMovieClip("square_mc", 1); square_mc.lineStyle(1, 0x000000, 100); square_mc.beginFill(0xFF0000, 100);...
  • Page 78 Number data type The Number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308. You can manipulate numbers using the arithmetic operators addition ( ), subtraction (-), multiplication ( ), division ( ), modulo (...
  • Page 79 The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. This example uses the methods: play() nextFrame() mcInstanceName.play(); mc2InstanceName.nextFrame(); You can also create custom objects to organize information in your Flash application. To add interactivity to an application with ActionScript, you need many pieces of information: for example, you might need a user’s name, age, and phone number;...
  • Page 80 To include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table lists all the ActionScript escape characters: Escape sequence Character...
  • Page 81 If your application has multiple frames, the code does not execute a second time because the variable is no longer undefined. init Void data type The Void data type has one value, , and is used in a function definition to indicate that void the function does not return a value, as shown in the following example: //Creates a function with a return type Void...
  • Page 82 You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes.
  • Page 83 To assign a specific data type to an item, specify its type using the keyword and post- colon syntax, as shown in the following example: // Strict typing of variable or object var myNum:Number = 7; var birthday:Date = new Date(); // Strict typing of parameters function welcome(firstName:String, age:Number) { // Strict typing of parameter and return value...
  • Page 84 Another advantage of strict data typing is that Flash automatically shows code hints for built- in objects when they are strictly typed. For more information, see “About assigning data types and strict data typing” on page Files published using ActionScript 1.0 do not respect strict data typing assignments at compile time, so assigning the wrong type of value to a variable that you have strictly typed doesn’t generate a compiler error.
  • Page 85 For example, the following code does not specify the data type of the parameter . At xParam runtime, you use the parameter to hold a value of type Number and then a value of type . The function then uses the operator to test whether the String dynamicTest()
  • Page 86: About Variables

    The following example shows how you can use the operator to return the kind of typeof object that you trace: // Create a new instance of LoadVars class. var my_lv:LoadVars = new LoadVars(); /* typeof operator doesn't specify class, only specifies that my_lv is an object */ var typeResult:String = typeof(my_lv);...
  • Page 87 It’s a good idea to assign a value to a variable the first time you declare the variable. Assigning an initial value is called initializing the variable, and it’s often done on Frame 1 of the Timeline or from within a class that loads when the SWF file begins to play. There are different kinds of variables, which are affected by scope.
  • Page 88 About declaring variables You can declare variables on a frame in the timeline, directly on an object, or within an external class file. Define variables using the keyword and follow the variable naming conventions. You can declare a variable called as shown in the following example: firstName, var firstName:String;...
  • Page 89 This example assigns the value of to the variable. When you declare the Pirate Eye catName variable, you can also assign a value to it instead of assigning it afterwards (as in the previous examples). You could set the variable when you declare it, as shown in the catName following example: var catName:String = "Pirate Eye";...
  • Page 90 If you want to create an array and assign values to it, the format is slightly different, as shown in the following code: var childrenArr:Array = new Array("Pylon", "Smithers", "Gil"); There is an alternative (shorthand) syntax for creating an array using array access operators, which use the bracket ( ) punctuators.
  • Page 91 When you assign a value, you use an operator to define a value to a variable. For example, the following script uses the assignment operator to assign a value of 7 to the variable numChildren var numChildren:Number = 7; If you want to change the value of the variable, use the following code: numChildren numChildren = 8;...
  • Page 92 The ActionScript editor supports code hints for built-in classes and for variables that are based on these classes. If you want Flash to provide code hints for a particular object type that you assign to a variable, you can strictly type the variable. Code hints provide tooltip-style syntax hints and a pop-up menu that helps you write your code quickly.
  • Page 93 Type the following code on Frame 1 of the Timeline. // Does not work function badClickListener(evt:Object):Void { getURL(targetUrl); var targetUrl:String = "http://www.macromedia.com"; bad_button.addEventListener("click", badClickListener); Select Control > Test Movie, and notice that the button does not work (it doesn’t open the web page).
  • Page 94 When you change to 30 (in line 3 of the code), the value of remains myNum otherNum because doesn’t look to for its value. The variable contains the otherNum myNum otherNum value of that it receives (in line 2 of the code). myNum Select Control >...
  • Page 95 To pass an object by reference: Select File > New and then select Flash Document to create a new FLA file, and save it as copybyref.fla. Select Frame 1 of the Timeline, and type the following code into the Actions panel: var myArray:Array = new Array("tom", "josie");...
  • Page 96 Select Control > Test Movie to test your ActionScript. The first statement in this ActionScript displays the original contents of the trace() array ( ). After you call the function and pass a reference to myArray 1,2,3 zeroArray() array, each of the array’s values are overwritten and set to zero. The myArray subsequent statement displays the new contents of the...
  • Page 97 Global variables Global variables and functions are visible to every timeline and scope in your document. To declare (or create) a variable with global scope, use the identifier before the variable _global name and do not use the syntax. For example, the following code creates the global var = variable myName...
  • Page 98 To use timeline variables in a document: Create a new Flash document, and name it timelinevar.fla. Add the following ActionScript to Frame 1 of the Timeline: var myNum:Number = 15; /* initialized in Frame 1, so it's available to all frames */ Select Frame 20 of the Timeline.
  • Page 99 If the variable name you use for your local variable is already declared as a timeline variable, the local definition takes precedence over the timeline definition while the local variable is in scope. The timeline variable will still exist outside of the function. For example, the following code creates a timeline string variable named , and then creates a local variable of the str1...
  • Page 100 The variables are often used as loop counters. In the following example, you use as a local variable; it exists only inside the function: initArray() var myArr:Array = new Array(); function initArray(arrayLength:Number):Void { var i:Number; for(i = 0; i < arrayLength; i++) { myArr[i] = i + 1;...
  • Page 101 You can use variables in different ways in a SWF file, depending on what you need the variables for. For more information, see the following topics: “Using variables from the URL” on page 101 “Using FlashVars in an application” on page 104 “Loading variables from a server”...
  • Page 102 <embed src="urlvariables.swf" quality="high" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> To pass variables from the generated HTML document to your Flash document, you can pass variables after the path and filename (urlvariables.swf). Add the bold text to the HTML file that was generated on your desktop.
  • Page 103 &) its URL-encoded equivalent ( Open the urlvariables.html document, and find the following code: ?myURL=http://weblogs.macromedia.com&myTitle=Macromedia+News+Aggregator Replace it with the following code: ?myURL=Ben+%26+Jerry&flavor=Half+Baked Save the revised HTML, and test your Flash document again. You see that Flash created the following name/value pairs.
  • Page 104 <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="myflashvars.swf" /> <param name="FlashVars" value="myURL=http://weblogs.macromedia.com/"> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="myflashvars.swf" FlashVars="myURL=http:// weblogs.macromedia.com/" quality="high" bgcolor="#ffffff" width="550" height="400" name="myflashvars" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> Data and Data Types...
  • Page 105 , which contains the string myURL . When the SWF file loads, a property named http://weblogs.macromedia.com myURL is created in the _level0 scope. One of the advantages of using FlashVars or passing variables along the URL is that the variables are immediately available in Flash when the SWF file loads.
  • Page 106 Select Control > Test Movie to test the document. If the file successfully loads, the event is called and the Output panel displays complete the value of . If the text file cannot be downloaded, the argument is set dayNames success and the Output panel displays the text false...
  • Page 107 Stage. Edit the generated HTML document in an editor (such as Dreamweaver or Notepad), and modify the default HTML to match the following text: <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" />...
  • Page 108: Organizing Data In Objects

    <embed src="urlvariables.swf" quality="high" FlashVars="imgURL=http:// www.helpexamples.com/flash/images/image2.jpg" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> Test the HTML document to see the changes. An image that you specify in the HTML code appears in the SWF file. To modify this example to use your own images, you would modify the FlashVars value (the string inside the double quotes).
  • Page 109 This code, which is one way to create a simple object, creates a new object instance and defines a few properties within the object. Now enter the following ActionScript after the code you entered in step 2. // The second way var secondObj:Object = {firstVar:"hello world", secondVar:28, thirdVar:new Date(1980, 0, 1)};...
  • Page 110: About Casting

    The following example presents another way to loop over objects. In this example, an object is created and looped over using a loop, and each property appears in the Output for..in panel: var myObj:Object = {var1:"One", var2:"Two", var3:18, var4:1987}; var i:String; for (i in myObj) { trace(i + ": "...
  • Page 111 About casting objects The syntax for casting is , where you want the compiler to behave as if the data type(item) type of the item is . Casting is essentially a function call, and the function call returns type if the cast fails at runtime (this occurs in files published for Flash Player 7 or later; files null published for Flash Player 6 do not have runtime support for failed casts).
  • Page 112 This example defines two string variables ( ), which are added firstNum secondNum together. The initial result is that the numbers are concatenated instead of added because they are a String data type. The second trace statement converts both numbers to a Number data type before performing the addition that yields the proper result.
  • Page 113: Chapter 5: Syntax And Language Fundamentals

    CHAPTER 5 Syntax and Language Fundamentals Learning ActionScript syntax and statements is like learning how to put together words to make sentences, which you can then put together into paragraphs. ActionScript can be as simple. For example, in English, a period ends a sentence; in ActionScript, a semicolon ends a statement.
  • Page 114: About Syntax, Statements, And Expressions

    For more information on working with ActionScript syntax and language fundamentals, see the following topics: About syntax, statements, and expressions ........114 About dot syntax and target paths .
  • Page 115 Expressions, different from statements, are any legal combination of ActionScript symbols that represent a value. Expressions have values, while values and properties have types. An expression can consist of operators and operands, values, functions, and procedures. The expression follows ActionScript rules of precedence and of association. Typically, Flash Player interprets the expression and then returns a value that you can use in your application.
  • Page 116 ActionScript does not support regular expressions using the RegExp object. However, Macromedia Central does support the RegExp object. For more information on Macromedia Central, see www.macromedia.com/software/central. About case sensitivity When you write ActionScript for Flash Player 7 and later, your code is case-sensitive. This means that variables with slightly different capitalization are considered different from each other.
  • Page 117 When you publish for versions of Flash Player (Flash Player 6 and earlier), Flash traces the string in the Output panel. Because Flash Player 7 and later versions are case-sensitive, Jimmy are two separate variables (when you use either ActionScript 1.0 firstName firstname or ActionScript 2.0).
  • Page 118: About Dot Syntax And Target Paths

    About dot syntax and target paths In ActionScript, you use a dot ( ) operator (dot syntax) to access properties or methods that belong to an object or instance on the Stage. You also use the dot operator to identify the target path to an instance (such as a movie clip), variable, function, or object.
  • Page 119 You name instances using an instance name, which you can specify in two different ways (both demonstrated below): Manually by selecting an instance and typing an instance name in the Property inspector (when an instance is on the Stage). Dynamically by using ActionScript. You create an instance using ActionScript and assign it an instance name when you create it.
  • Page 120 Select Modify > Convert to Symbol, select the Movie Clip option, and then click OK to create the symbol. Select the movie clip on the Stage and give it the instance name myClip in the Property inspector. Insert a new layer and rename the layer actions. Add the following ActionScript to Frame 1 of the actions layer: myClip._xscale = 50;...
  • Page 121 If you work with nested movie clips that have their own timelines, you can manipulate the playhead in a nested instance’s timeline using code similar to the following snippet: myClip.nestedClip.gotoAndPlay(15); myClip.someOtherClip.gotoAndStop("tweenIn"); Notice that the clip that you manipulate (such as ) appears right before the nestedClip action.
  • Page 122 Type the following ActionScript after the code you added in step 3: rotateClip.loadMovie("http://www.helpexamples.com/flash/images/ image1.jpg"); This code loads an image into the rotateClip movie clip that you created with code. You’re targeting the rotateClip instance with ActionScript. Select Control > Test Movie to test your document. Now you should see an image on the Stage that rotates 50º...
  • Page 123 About scope and targeting When you nest instances, the movie clip that nests a second movie clip is known as the parent to the nested instance. The nested instance is known as the child instance. The main Stage and main timeline are essentially a movie clip themselves, and can therefore be targeted as such.
  • Page 124: About Language Punctuators

    Using the Target Path button Sometimes it takes some time to figure out what a given target path is, or what target path you need for a piece of code. If you target an instance you have on the Stage, you can use the Target Path button to determine what the path is to that instance.
  • Page 125 For more information on the dot ( ) operator and array access ( ) operators, see “Using dot and array access operators” on page 184. For information on white space and code formatting, “Formatting ActionScript syntax” on page 764. Semicolons and colons ActionScript statements terminate with a semicolon ( ) character, as demonstrated in the following two lines of code:...
  • Page 126 You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. In the following snippet, you create a new object of the custom type Student: var firstStudent:Student = new Student();...
  • Page 127 In the following example, you create both an event listener object and a MovieClipLoader instance. var imgUrl:String = "http://www.helpexamples.com/flash/images/image1.jpg"; this.createEmptyMovieClip("img_mc", 100); var mclListener:Object = new Object(); mclListener.onLoadStart = function() { trace("starting"); mclListener.onLoadInit = function(target_mc:MovieClip):Void { trace("success"); mclListener.onLoadError = function(target_mc:MovieClip):Void { trace("failure");...
  • Page 128 Save the class file. Select File > New and click Flash Document to create a new FLA file. Save the new FLA file as student_test.fla. Type the following ActionScript on Frame 1 of the main Timeline: // student_test.fla import Student; var firstStudent:Student = new Student("cst94121", "John", "H.", "Doe");...
  • Page 129 Select File > Save to save the Flash document. Select Control > Test Movie to test the code in the authoring environment. In the SWF file, an error message is displayed if you click the Button instance on the Stage when you do not have text in the TextInput component.
  • Page 130 Because of order of precedence, if you didn’t use parentheses or use two separate statements, the multiplication would be computed first, meaning that the first operation would be 20 * 0.8. The result, 16, would then be added to the current value of circleClip._x and finally assigned to the variable.
  • Page 131 Literals can also be used to initialize a generic object. A generic object is an instance of the Object class. Object literals are enclosed in curly braces ( ) and use the comma punctuator ) to separate object properties. Each property is declared with the colon punctuator ( which separates the name of the property from the value of the property.
  • Page 132 Avoid using cluttered comments. An example of cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation around your comments. Instead, use white space to separate your comments from the ActionScript. If you format your ActionScript using the Auto Format button in the Actions panel or Script window, this removes the white space.
  • Page 133 Multiline comments Use multiline comments, also called block comments, for comments that are several lines in length. Developers commonly use multiline comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method.
  • Page 134 Pelican class version 1.2 10/10/2005 copyright Macromedia, Inc. Use block comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method. There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments.
  • Page 135: About Constants And Keywords

    Include one documentation comment per class, interface, or member, and place it directly before the declaration. If you have additional information to document that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments). Implementation comments directly follow the declaration.
  • Page 136 Variables should be lowercase or mixed-case letters; however, constants (variables that do not change) should be uppercase. Separate words with underscores, as the following ActionScript shows: var BASE_URL:String = "http://www.macromedia.com"; //constant var MAX_WIDTH:Number = 10; //constant Write static constants in uppercase, and separate words with an underscore. Do not directly...
  • Page 137 For example, the class definition in the next example creates three constants that follow the naming convention used by ActionScript 2.0. To use constants in an application: Select File > New and then select ActionScript File to create an AS file. Name the new file ConstExample.as.
  • Page 138 Type the following code into the Actions panel: var myExample:ConstExample = new ConstExample(); trace(myExample.EXAMPLE_PUBLIC); // output: Public access This code instantiates the myExample instance and accesses the EXAMPLE_PUBLIC property. Select Control > Test Movie to test your document. You see in the Output panel.
  • Page 139 About reserved words Reserved words are words that you cannot use as identifiers in your code because the words are reserved for use by ActionScript. Reserved words include keywords, which are ActionScript statements, and words that are reserved for future use. That means you should not use them for naming your variables, instances, custom classes, and so on;...
  • Page 140 All built-in class names, component class names, and interface names are reserved words, and should not be used as identifiers in your code: Accessibility Accordion Alert Array Binding Boolean Button Camera CellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMenu ContextMenuItem CustomActions CustomFormatter CustomValidator DataGrid...
  • Page 141: About Statements

    To learn what these names are, refer to the ActionScript 2.0 Language Reference, and search the Help panel for additional instructional and usage sections in this book (Learning ActionScript 2.0 in Flash). About statements A statement is an instruction you give the FLA file to do something, such as to perform a particular action.
  • Page 142 For more information on each statement, see the following topics: “About compound statements” on page 142 “About conditions” on page 142 “Repeating actions using loops” on page 153 About compound statements A compound statement contains numerous statements that you enclose within curly brace ) punctuators.
  • Page 143 For more information on conditions that you can use, and how to write them, see the following topics: “About writing conditions” on page 143 “Using the if statement” on page 144 “Using the if..else statement” on page 145 “Using the if..else if statement” on page 146 “Using a switch statement”...
  • Page 144 Using the if statement Use the statement when you want to execute a series of statements based on a whether a certain condition is true. // if statement if (condition) { // statements; There are several times when you’ll use statements when you work on a Flash project.
  • Page 145 Using the if..else statement conditional statement lets you test a condition and then execute a block of if..else code if that condition exists or execute an alternative block of code if the condition does not exist. For example, the following code tests whether the value of exceeds 20, generates a trace() statement if it does, or generates a different...
  • Page 146 Using the if..else if statement You can test for more than one condition using the conditional statement. You if..else if use the following syntax in an statement: if..else if // else-if statement if (condition) { // statements; } else if (condition) { // statements;...
  • Page 147 Select Control > Test Movie to test the ActionScript. In this code, you create a string called that holds the current hour number currentHour (for example, if it’s 6:19 pm, holds the number ). You use the currentHour method of the Date class to get the current hour. Then you can use the getHours() statement to trace information to the Output panel, based on the number if..else if...
  • Page 148 To use a switch statement in a document: Select File > New and then select Flash Document. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel: var listenerObj:Object = new Object(); listenerObj.onKeyDown = function() { // Use the String.fromCharCode() method to return a string.
  • Page 149 Using try..catch and try..catch..finally statements Using blocks lets you add error handling to your Flash applications. try..catch..finally keywords let you enclose a block of code where an error can try..catch..finally occur and respond to that error. If any code within the code block throws an error (using statement), control passes to the block, if one exists.
  • Page 150 To use the try..catch..finally block for data validation before dividing some numbers: Select File > New and then select Flash Document. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel: var n1:Number = 7; var n2:Number = 0;...
  • Page 151 To create a custom error: Select File > New and create a new ActionScript file. Select File > Save As and name the file DivideByZeroException.as. Type the following ActionScript into the Script pane: // In DivideByZeroException.as: class DivideByZeroException extends Error { var message:String = "Divide By Zero error";...
  • Page 152 About the conditional operator and alternative syntax If you like shortcuts, you can use the conditional ( ) operator, also called conditional expressions. The conditional operator lets you convert simple statements into a if..else single line of code. The operator helps decrease the amount of code you write while accomplishing the same thing, but it also tends to make your ActionScript more difficult to read.
  • Page 153 When you write complex conditions, it is good form to use parentheses [ ] to group conditions. If you do not use parentheses, you (or others working with your ActionScript) might run into operator precedence errors. For more information on operator precedence, see “About operator precedence and associativity”...
  • Page 154 The most common type of loop is the loop, which loops over a block of code a predefined number of times. For example, if you have an array of items, and you want to perform a series of statements on each item in the array, you would use a loop and loop from 0 to the number of items in the array.
  • Page 155 To repeat an action using a built-in counter: Use the statement. Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes.
  • Page 156 For more information on the statement, see “Using for..in loops” on page 158. for..in Iterations in Flash execute very quickly in the Flash Player, but loops depend heavily on the processor. The more iterations a loop has and the more statements executed within each block, the more processor resources will be consumed.
  • Page 157 When you work with loops (and especially loops), always make sure while do..while that the loop can exit properly and does not end up in an infinite loop. For more information on controlling loops, see “Using a switch statement” on page 147.
  • Page 158 Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel: var i:Number; for (i = 0; i < 5; i++) { this.attachMovie("libraryLinkageClassName", "clip" + i + "_mc", i, {_x:(i * 100)}); Select Control > Test Movie to test the code in Flash Player. Notice how five movie clips duplicate across the top of the Stage.
  • Page 159 This code outputs the following in the Output panel: three For more information on objects and properties, see “Object data type” on page You cannot iterate through the properties of an object if it is an instance of a custom class, unless the class is a dynamic class.
  • Page 160 Using while loops Use the statement to repeat an action while a condition exists, similar to an while statement that repeats as long as the condition is true loop evaluates an expression and executes the code in the body of the loop if the while expression is .
  • Page 161 Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel: var users_ds:mx.data.components.DataSet; users_ds.addItem({name:"Irving", age:34}); users_ds.addItem({name:"Christopher", age:48}); users_ds.addItem({name:"Walter", age:23}); users_ds.first(); while (users_ds.hasNext()) { trace("name:" + users_ds.currentItem["name"] + ", age:" + users_ds.currentItem["age"]); users_ds.next(); Select Control > Test Movie to test the document. The following information is displayed in the Output panel: name:Irving, age:34 name:Christopher, age:48...
  • Page 162 Using nested loops in your ActionScript The following example demonstrates how to make an array of objects and display each of the values in the nested structure. This example shows you how to use the loop to loop through each item in the array and how to use the loop to iterate through each key/ for..in value pair in the nested objects.
  • Page 163: About Arrays

    About arrays An array is an object whose properties are identified by numbers representing their positions in the structure. Essentially, an array is a list of items. It’s important to remember that each element in an array doesn’t have to be the same data type. You can mix numbers, dates, strings, and objects and even add a nested array at each array index.
  • Page 164 ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.
  • Page 165 ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.
  • Page 166 ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.
  • Page 167 ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.
  • Page 168 ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.
  • Page 169 To create an indexed array: Create a new Flash document, and save it as indexArray.fla. Add the following ActionScript to Frame 1 of the Timeline: var myArray:Array = new Array(); myArray.push("one"); myArray.push("two"); myArray.push("three"); trace(myArray); // one,two,three In the first line of ActionScript, you define a new array to hold the values. Select Control >...
  • Page 170 To create a basic multidimensional array and retrieve elements from the array: Create a new Flash document, and save it as multiArray1.fla. Add the following ActionScript to Frame 1 of the Timeline: var twoDArray:Array = new Array(new Array("one","two"), new Array("three", "four")); trace(twoDArray);...
  • Page 171 for (j = 0; j < gridSize; j++) { mainArr[i][j] = "[" + i + "][" + j + "]"; trace(mainArr); This ActionScript creates a 3 x 3 array and sets the value of each array node to its index. Then you trace the array ( mainArr Select Control >...
  • Page 172 Select Control > Test Movie to view the elements that are displayed in the Output panel. You will see the following in the Output panel: [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2] For information on using arrays, see “Using arrays”...
  • Page 173 Type the following ActionScript on Frame 1 of the Timeline: // Define the object to use as an associative array. var someObj:Object = new Object(); // Define a series of properties. someObj.myShape = "Rectangle"; someObj.myW = 480; someObj.myH = 360; someObj.myX = 100;...
  • Page 174 To create an associative array using an Object constructor: Create a new Flash document, and save it as assocArray.fla. Add the following ActionScript to Frame 1 of the Timeline: var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"}; trace(monitorInfo["type"] + ", " + monitorInfo["resolution"]); This code creates an associative array called , and uses an object literal to monitorInfo...
  • Page 175 The second way to create an associative array is to use the Array constructor and then use either the bracket operator ( ) or the dot operator ( ) to add key and value pairs to the array. If you declare your associative array to be of type Array, you cannot use an object literal to initialize the array.
  • Page 176: About Operators

    About operators This section describes general rules about common types of operators, operator precedence, and operator associativity. Operators are characters that specify how to combine, compare, or change values in an expression. An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function.
  • Page 177 “About multiplicative operators” on page 187 “About additive operators” on page 187 “Using numeric operators” on page 188 “About relational operators” on page 189 “About equality operators” on page 189 “Using relational and equality operators” on page 190 “About assignment operators” on page 193 “Using assignment operators”...
  • Page 178 To manipulate values using operators: Create a new Flash document. Open the Actions panel (Window > Actions) and type the following code into the Script pane: // example one var myScore:Number = 0; myScore = myScore + 1; trace("Example one: " + myScore); // 1 // example two var secondScore:Number = 1;...
  • Page 179 You can manipulate the value of a variable using operators while a condition is . For true example, you can use the increment operator ( ) to increment the variable while the condition is true. In the following code, the condition is while is less than the value of true...
  • Page 180 It’s also possible for operators to have the same precedence. In this case, the associativity determines the order in which the operators perform. You can either have left-to-right associativity or right-to-left associativity. Take a look at the multiplication operator again. It has left-to-right associativity, so the following two statements are the same.
  • Page 181 The following table lists all the ActionScript operators and their associativity, from highest to lowest precedence. For more information and guidelines on using operators and parentheses, Chapter 19, “Formatting ActionScript syntax,” on page 764. Operator Description Associativity Highest precedence Post-increment Left to right Post-decrement Left to right...
  • Page 182 Operator Description Associativity Less than or equal to Left to right <= Greater than Left to right > Greater than or equal to Left to right >= Equal Left to right Not equal Left to right Bitwise AND Left to right &...
  • Page 183 In this ActionScript, the method of the Array class reorders the contents of the array sort() alphabetically. You can see that the value “Egg” comes before the value “chicken” because uppercase E comes before a lowercase c. If you want to compare the strings regardless of case, you need to convert the strings to uppercase or lowercase before you compare them.
  • Page 184 The previous example shows how you can use the addition (+) and addition assignment (+=) operators to concatenate strings. Notice how the third line of code uses the addition operator to concatenate the value of the variable into the text field, and the fourth line of code myNum uses the addition assignment operator to concatenate a string onto the existing value of the text field.
  • Page 185 Add the following ActionScript to Frame 1 of the Timeline: myClip.spam = 5; trace(myClip.spam); // 5 If you want to set a value in the myClip instance on the current timeline you can use the dot or array access operators, as demonstrated in this ActionScript. If you write an expression inside the array access operator, it evaluates that expression first and uses the result as the variable name.
  • Page 186 About postfix operators The postfix operators take one operator and either increment or decrement the operator’s value. Although these operators are unary operators, they are classified separately from the rest of the unary operators because of their higher precedence and special behavior. For information on unary operators, see “About unary operators”...
  • Page 187 All of the operators in this table have equal precedence: Operator Operation performed Increment (prefix) Decrement (prefix) Unary + Unary - (negation) Returns type information typeof Returns undefined value void About multiplicative operators The multiplicative operators take two operands and perform multiplication, division, or modulo calculations.
  • Page 188 Using numeric operators You use numeric operators to add, subtract, divide, and multiply values in ActionScript. You can perform different kinds of arithmetic operations. One of the most common operators is the increment operator, commonly formed as . There are more things you can do with this operator.
  • Page 189 About relational operators The relational operators take two operands, compare their values, and return a Boolean value. All of the operators in this table have equal precedence: Operator Operation performed Less than < Greater than > Less than or equal to <= Greater than or equal to >=...
  • Page 190 Using relational and equality operators Relational and equality operators, also called comparison operators, compare values of expressions, and they return either (a Boolean value). You frequently use true false comparison operators in conditional statements and loops to specify the condition for when the loop should stop.
  • Page 191 Select Control > Test Movie again. The string doesn’t appear in the Output panel. It equals 2 Return to the authoring environment and change: if (myNum == 2) { if (myNum = 2) { Select Control > Test Movie again. The string appears in the Output panel again.
  • Page 192 To use the greater than or equal to operator in your code: Select File > New and then select Flash Document to create a new FLA file. Add the following code to Frame 1 of the main Timeline: this.createTextField("myTxt", 20, 0, 0, 100, 20); myTxt.type = "input";...
  • Page 193 Except for the strict equality ( ) operator, the comparison operators compare strings only if both operands are strings. If only one of the operands is a string, both operands convert to numbers and perform a numeric comparison. For more information on strings and operators, “About using operators with strings”...
  • Page 194 Using assignment operators You can use the assignment operator (=) to assign a given value to a variable. You might assign a string to a variable, as follows: var myText:String = "ScratchyCat"; You can also use the assignment operator to assign several variables in the same expression. In the following statement, the value of 10 is assigned the variables , and numOne...
  • Page 195 Using logical operators You often use logical operators with comparison operators to determine the condition of an statement. This is demonstrated by the next example. To use logical operators in your code: Select File > New and create a new Flash document. Open the Actions panel and type the following ActionScript on Frame 1 of the Timeline: this.createTextField("myTxt", 20, 0, 0, 100, 20);...
  • Page 196 When you use operands, you need to be careful of the order. This is particularly the case when you use complex conditions. In the following snippet, you can see how you use the logical AND operator to check that a number is between 10 and 20. Based on the result, you display an appropriate message.
  • Page 197 About bitwise logical operators The bitwise logical operators take two operands and perform bit-level logical operations. The bitwise logical operators differ in precedence and are listed in the table in order of decreasing precedence: Operator Operation performed Bitwise AND & Bitwise XOR Bitwise OR For information on using bitwise operators, see...
  • Page 198 The first line defines an array of random names and traces them to the Output panel. Then you call the method and specify two sort options using the constant Array.sort() values . The result of the sort method Array.CASEINSENSITIVE Array.DESCENDING causes the items in the array to be sorted in reverse order (z to a).
  • Page 199 About the conditional operator The conditional operator is a ternary operator, which means that it take three operands. The conditional operator is a short-hand method of applying the conditional statement: if..else Operator Operation performed Conditional For information on using the conditional operator and an example, see “About the conditional operator and alternative syntax”...
  • Page 200 Select Control > Test Movie. The Output panel displays the following text: You got 11 out of 13 answers correct, for a score of 84.62%. When you call in this example, the score rounds to the nearest integer (85) Math.round() and is displayed in the Output panel.
  • Page 201: Chapter 6: Functions And Methods

    CHAPTER 6 Functions and Methods Understanding functions is important when you’re writing ActionScript, creating classes, and using methods.There are several different kinds of functions that you’ll work with. In this chapter, you learn about functions and methods: how to use them in your applications when you use built-in classes, and how to write them.
  • Page 202 If you pass values as parameters to a function, the function can perform calculations using the supplied values. Each function has individual characteristics, and some functions require that you pass certain types or numbers of values. If you pass more parameters than the function requires, the function ignores the extra values.
  • Page 203 For more information on passing parameters, see “Passing parameters to a function” on page 218. There are numerous kinds of functions that you can write. For more information on writing functions, as well as links to sections on writing specific kinds of functions, see “About types of methods and functions”...
  • Page 204 class Person { public static var numPeople:Number = 0; // instance members private var _speed:Number; // constructor public function Person(speed:Number) { Person.numPeople++; this._speed = speed; // static methods public static function getPeople():Number { return Person.numPeople; // instance methods public function walk(speed:Number):Void { this._speed = speed;...
  • Page 205 To add a top-level function call to your code, just add a single line of code in the Script pane of the Actions panel. For example, type the following: trace("my message"); When you test the SWF file with this single line of code, the top-level function is trace() called, and text appears in the Output panel.
  • Page 206 You can use functions that are built into the ActionScript language. They might be top level, as described in “About types of methods and functions” on page 203; or the function might be in a built-in class, such as Math or MovieClip, which you use as a method in your application.
  • Page 207 Writing named functions A named function is a kind of function that you commonly create in your ActionScript code to carry out all kinds of actions. When you create a SWF file, the named functions are compiled first, which means that you can reference the function anywhere in your code, as long as the function has been defined in the current or a previous frame.
  • Page 208 Select Control > Test Movie to test the SWF file. You use the statement to create your own function in ActionScript. Remember that function parameters are optional; however, if you don’t have parameters, you still need to include the brackets. The content between the curly braces ( ) is called the function block.
  • Page 209 For example, sometimes you need to write ActionScript to handle data that loads into a SWF file from the server. After you finish loading data into a SWF file, you can access the data from that location. It's important to use ActionScript to check whether the data has been fully loaded.
  • Page 210 Similarly, the following code placed on any frame does not work: myWidth(); var myWidth:Function = function () { trace(my_mc._width); However, this code works properly: var myWidth:Function = function () { trace(my_mc._width); myWidth(); You could also place on any frame that is after the frame that contains the myWidth() function.
  • Page 211 About function literals A function literal is an unnamed function that you declare in an expression instead of in a statement. Function literals are useful when you need to use a function temporarily or to use a function in your code where you might use an expression instead. The syntax for a function literal is: function (param1, param2, etc) { // statements...
  • Page 212 Defining global and timeline functions “About functions and methods” on page 201, you explored the different kinds of functions that are available in Flash. As with variables, functions are attached to the timeline of the movie clip that defines them, and you must use a target path to call them. As with variables, you can use the identifier to declare a global function that is available to all timelines _global...
  • Page 213 Targeting and calling user-defined functions User-defined functions are simply functions that you create yourself to use in applications, as opposed to functions in built-in classes that perform predefined functions. You name the functions yourself and add statements in the function block. Previous sections cover writing functions such as named, unnamed, and callback functions.
  • Page 214 Select Control > Test Movie to test the Flash document. For more information on named functions, see “Writing named functions” on page 207. Classes contain many user-defined functions. For information on writing functions in class files, see “Using functions in Flash” on page 214.
  • Page 215 You can create functions in a FLA file or a class file or write ActionScript code that resides in a code-based component. The following examples show you how to create functions on a timeline and in a class file. By packing your code into class files or code-based components, you can easily share, distribute, or reuse blocks of code.
  • Page 216 Anonymous functions are often more difficult to read. Compare the following code to the preceding code. var myCircle:Function = function(radius:Number):Number { // function block here return (Math.PI * radius * radius); trace(myCircle(5)); You can also place functions in class files when you use ActionScript 2.0, as the following example shows: class Circle { public function area(radius:Number):Number {...
  • Page 217 return Number.NaN; num_array.sort(Array.NUMERIC | Array.DESCENDING); var min:Number = Number(num_array.pop()); return min; public static function arrayMax(num_array:Array):Number { if (num_array.length == 0) { return undefined; num_array.sort(Array.NUMERIC); var max:Number = Number(num_array.pop()); return max; Select File > Save to save the ActionScript file. Create a new Flash document and save it as classFunctions.fla in the same directory as Utils.as.
  • Page 218 Using variables in functions Local variables are valuable tools for organizing code and making it easy to understand. When a function uses local variables, it can hide its variables from all other scripts in the SWF file; local variables are invoked in the scope of the body of the function and cease to exist when the function exits.
  • Page 219 After passing the parameter, you can pass a value to the function when you call the function. This value traces in the Output panel, as follows: myFunc("This is what traces"); When you call the function, you should always pass the specified number of parameters unless your function checks for undefined values and sets default values accordingly.
  • Page 220 Type the following code after the function: var area:Number = getArea(10, 12); trace(area); // 120 function call assigns the values 10 and 12 to the width and height, getArea() respectively, and you save the return value in the instance. Then you trace the values area that you save in the instance.
  • Page 221 The following rules govern how to use the statement in functions: return If you specify a return type other than Void for a function, you must include a return statement and it must be followed by the returned value in the function. If you specify a return type of Void, you do not need to include a statement, but if return...
  • Page 222: Understanding Methods

    About nested functions You can call a function from inside another function. This lets you nest functions so that you can have them perform specific tasks in Flash. For example, you can nest functions on a timeline to perform specific tasks on a string. Type the following code on Frame 1 of the Timeline: var myStr:String = "My marshmallow chicken is yellow.";...
  • Page 223 You use the method of the Array class to create a new Array object named sortOn() . The array is populated by three objects that contain a first name and age, and userArr then the array is sorted based on the value of each object’s property.
  • Page 224 When you use this ActionScript, you are calling the method of the eatCabbage() EatingHabits class. When you use methods of any built-in class (in addition to the custom class you wrote earlier in this procedure), you are using a method on a timeline. After the previous line of ActionScript, add the following code: function eatCarrots():Void { trace("tastes good");...
  • Page 225: Chapter 7: Classes

    This chapter introduces you to using and writing classes using ActionScript 2.0. Classes are the backbone of ActionScript 2.0, and are more important than they were in earlier versions of Macromedia Flash. You will learn how important classes are in Flash throughout this chapter.
  • Page 226: About Object-Oriented Programming And Flash

    For more information on working with custom and built-in classes, see the following topics: About object-oriented programming and Flash ......226 Writing custom class files .
  • Page 227 Flash Player 8, available in both Flash Basic 8 and Flash Professional 8, adds several new features to the ActionScript language such as filter effects, file upload and download, and the External API. As always, ActionScript 2.0 provides several powerful and familiar OOP concepts and keywords (such as , and found in other...
  • Page 228 When you use a class, you can also extend existing classes and add new functionality or modify existing functionality. For example, if you create three very similar classes, you can write a base class and then write two other classes that extend the base class. These two classes can add additional methods and properties, so that you don’t need to create three class files that all duplicate the same code and logic.
  • Page 229 Because these three class files are related, you might decide to put them in a package (directory) called Shapes. In this case, the fully qualified class name would contain the package path, as well as the simple class name. Package paths are denoted with dot (.) syntax, where each dot indicates a subdirectory.
  • Page 230 Working with packages Packages are directories that contain one or more class files and reside in a designated classpath directory. For example, the flash.filters package is a directory on your hard disk that contains several class files for each filter type (such as BevelFilter, BlurFilter, DropShadowFilter, and so on) in Flash 8.
  • Page 231 statement applies only to the current script (frame or object) in which it’s called. import For example, suppose on Frame 1 of a Flash document you import all the classes in the macr.util package. On that frame, you can reference classes in that package by their class names instead of their fully qualified names.
  • Page 232 The following sections use the analogy of a cat, demonstrating how cats might compare to OOP concepts. Objects Think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In the world of OOP, objects also have properties and behaviors.
  • Page 233 One of the major benefits of using a superclass/subclass structure is that it is easier to reuse similar code between various classes. For example, you could build a superclass called Animal, which contains common characteristics and behaviors of all animals. Next you could build several subclasses that inherit from the Animal superclass and add characteristics and behaviors specific to that type of animal.
  • Page 234 Encapsulation In elegant object-oriented design, objects are seen as “black boxes” that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation.
  • Page 235: Writing Custom Class Files

    Writing custom class files The following example examines the parts of a class file. You learn how to write a class, and how you can modify the class to extend the ways that you can use it with Flash. You learn about the parts of a class and how to import them as well as related information about working with custom class files in Flash.
  • Page 236 Type the following ActionScript code into the Script window: User class author: John Doe version: 0.8 modified: 08/21/2005 copyright: Macromedia, Inc. This code defines a custom User class that allows you to create new users and specify user login information. class User { // private instance variables private var __username:String;...
  • Page 237 The User class’s constructor statement takes two parameters: p_username , which are copied into the class’s private instance variables p_password __username . The remainder of the code in the class defines the getter and setter __password properties for the private instance variables. If you want to create a read-only property, then you would define a getter function, but not a setter function.
  • Page 238: About Working With Custom Classes In An Application

    XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 239 XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 240 When you import class files, the following rules apply: statements can exist in the following locations: import Anywhere before the class definition in class files Anywhere in frame or object scripts Anywhere in ActionScript files that you include in an application (using the #include statement).
  • Page 241 Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Classes. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Classes. Do not delete the absolute global classpath. Flash uses this classpath to access built-in classes. If you accidentally delete this classpath, reinstate it by adding $(LocalData)/Classes as a new classpath.
  • Page 242 The relative path portion of the global classpath is denoted by a single dot ( ) and points to the current document directory. Be aware that relative classpaths can point to different directories, depending on the location of the document being compiled or published. You can use the following steps to add a global classpath or edit an existing classpath.
  • Page 243 For example, you might create a directory such as the following for your custom classes: Windows: Hard Disk\Documents and Settings\user\custom classes. Macintosh: Hard Disk/Users/user/custom classes. Then, you would add this path to the list of global classpaths (see “Using a global classpath” on page 241).
  • Page 244 Using a class file in Flash To create an instance of an ActionScript class, use the operator to invoke the class’s constructor function. The constructor function always has the same name as the class and returns an instance of the class, which you typically assign to a variable. For example, if you were using the User class from “Writing custom class files”...
  • Page 245 Using methods and properties from a class file In OOP, members (properties or methods) of a class can be instance members or class members. Instance members are created for each instance of the class; they are defined to the prototype of the class when they are initialized in the class definition. In contrast, class members are created once per class.
  • Page 246 Type the following ActionScript code into the Script window: Picture class author: John Doe version: 0.53 modified: 6/24/2005 copyright: Macromedia, Inc. The Picture class is used as a container for an image and its URL. class Picture { private var __infoObj:Object; public function Picture(src:String) { this.__infoObj = new Object();...
  • Page 247 XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 248 Public methods and properties keyword specifies that a variable or function is available to any caller. Because public variables and functions are public by default, the keyword is used primarily for stylistic this and readability benefits, indicating that the variable exists in the current scope. For example, you might want to use the keyword for consistency in a block of code that also contains this...
  • Page 249 If you want to add a private property to the previous class, you simply use the keyword before the keyword. private If you attempt to access the private property from outside the Sample class, you get a compiler error and a message in the Output panel. The message indicates that the member is private and cannot be accessed.
  • Page 250 XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 251 Similarly, any function declared within a class is considered a method of the class. In the Person class example, you can create a method called getInfo() class Person { public var age:Number; public var username:String; public function getInfo():String { // getInfo() method definition In the previous code snippet the Person class’s method, as well as the getInfo()
  • Page 252 XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 253 Type the following ActionScript code into the Script window: Singleton class author: John Doe version: 0.53 modified: 6/24/2008 copyright: Macromedia, Inc. class Singleton { private static var instance:Singleton = null; public function trackChanges():Void { trace("tracking changes."); public static function getInstance():Singleton { if (Singleton.instance == null) {...
  • Page 254 Remember not to use too few or too many class files for your application, because doing so can lead to poorly designed class files, which are not beneficial to the application’s performance or to your workflow. You should always attempt to use class files instead of placing code in other places (such as timelines);...
  • Page 255 In widget_test.fla, type the following code into Frame 1 of the Timeline: // Before you create any instances of the class, // Widget.widgetCount is zero (0). trace("Widget count at start: " + Widget.widgetCount); // 0 var widget1:Widget = new Widget(); // 1 var widget2:Widget = new Widget();...
  • Page 256 When you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes.
  • Page 257 Save the ActionScript document as Login.as. As you can see, returns the current value of , and getUserName() userName sets the value of to the string parameter passed to the method. setUserName() userName Select File > New and then select Flash Document to create a new FLA, and save it as login_test.fla in the same directory as Login.as.
  • Page 258 To use implicit getter and setter methods: Select File > New and then select ActionScript File, and then click OK. Type the following code into the Script window: class Login2 { private var __username:String; public function Login2(username:String) { this.__username = username; public function get userName():String { return this.__username;...
  • Page 259 Save the Flash document and select Control > Test Movie to test the file. Flash displays the following information in the Output panel: RickyM EnriqueI You cannot use getter and setter method attributes in interface method declarations. About dynamic classes Adding the keyword to a class definition specifies that objects based on the specified dynamic...
  • Page 260 Add the following code to create a new instance of the Person class ( ), and try firstPerson to assign a value to a property called (which doesn’t exist in the Person class): hairColor var firstPerson:Person = new Person(); firstPerson.hairColor = "blue"; // Error. There is no property with the name 'hairColor'.
  • Page 261 Save your changes to the person2_test.fla file. Select Control > Test Movie to test the code. Because the custom Flash class is dynamic, you can add methods and properties to the class at runtime (when the SWF file plays). When you test the code the text should blue be displayed in the Output panel.
  • Page 262 Depending on the coding environment you use, adding prefixes might also trigger code hints. You do not have to add these prefixes, and some developers feel it is unnecessary. Macromedia recommends adding the keyword as a prefix, because it can aid this readability and helps you write clean code by providing context for your methods and variables.
  • Page 263: Example: Writing Custom Classes

    Example: Writing custom classes Now that you’ve explored the basics of a class file, and what kinds of things it contains, it’s time to learn some of the general guidelines for creating a class file. The first example in this chapter shows you how to write classes and package them.
  • Page 264 XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 265 This code declares the same variable inside an inner block. Do not assign many variables to a single value in a statement, because it is difficult to read, as you can see in the following ActionScript code samples: // bad form xPos = yPos = 15;...
  • Page 266 240. Class files are also called ActionScript (AS) files. You create AS files in the Flash authoring tool or by using an external editor. Several external editors, such as Macromedia Dreamweaver and Macromedia Flex Builder, can create AS files. The name of a class (ClassA) must exactly match the name of the AS file that contains it (ClassA.as).
  • Page 267 ClassA.as created in an earlier step. Type the following code into the Script window: class com.macromedia.utils.ClassB { The previous code creates a new class named ClassB in the com.macromedia.utils package. Save your changes to both the ClassA.as and ClassB.as class files.
  • Page 268 For example, if your package was named , you would need to com.macromedia.utils create a directory structure of com/macromedia/utils and place your classes in the utils folder. Use the com.macromedia.utils prefix for any class you create in this package. For example, if your class name was ClassA, the full class name would need to be within the com.macromedia.utils.ClassA...
  • Page 269 Open the ClassA.as class file in the Flash authoring tool. Modify the existing class file so it matches the following code (the changes to make appear in boldface): class com.macromedia.utils.ClassA { function ClassA() { trace("ClassA constructor"); The previous code defines a constructor method for the ClassA class. This constructor traces a simple string to the Output panel, which will let you know when a new instance of the class has been created.
  • Page 270 To add properties to the ClassA and ClassB classes: Open ClassA.as and ClassB.as in the Flash authoring tool. Modify the ClassA.as ActionScript file to match the following code (the changes to make appear in boldface): class com.macromedia.utils.ClassA { static var _className:String; function ClassA() { trace("ClassA constructor");...
  • Page 271 To add methods to the ClassA and ClassB classes: Open ClassA.as and ClassB.as in the Flash authoring tool. Modify the ClassA class file so it matches the following code (the changes to make appear in boldface): class com.macromedia.utils.ClassA { static var _className:String; function ClassA() { trace("ClassA constructor");...
  • Page 272 Open ClassA.as and ClassB.as in the Flash authoring tool. Modify the ClassA class file so the code matches the following ActionScript (the changes to make appear in boldface): class com.macromedia.utils.ClassA { static var _className:String = "ClassA"; function ClassA() { trace("ClassA constructor");...
  • Page 273 Open ClassA.as and ClassB.as in the Flash authoring tool. Modify the ClassA.as ActionScript file so its contents match the following ActionScript (the changes to make appear in boldface): class com.macromedia.utils.ClassA { private static var _className:String = "ClassA"; public function ClassA() { trace("ClassA constructor");...
  • Page 274 Frame 1 of the Timeline in a FLA file, would result in a compiler error indicating that the method is private and can’t be accessed: import com.macromedia.utils.ClassA; var a:ClassA = new ClassA(); trace(a._className); // Error. The member is private and cannot be accessed.
  • Page 275 Modify the ClassA class file and add the new code to the top of the class file (the changes to make appear in boldface): ClassA class version 1.1 6/21/2005 copyright Macromedia, Inc. class com.macromedia.utils.ClassA { private static var _className:String = "ClassA"; public function ClassA() { trace("ClassA constructor");...
  • Page 276: Example: Using Custom Class Files In Flash

    Within the com folder, add a new folder named macromedia. Add a third, and final, subdirectory within the macromedia folder named utils. Save both the ClassA.as and ClassB.as class files within this utils folder. Now you are ready to proceed with this example.
  • Page 277 You can also use the fully qualified class name to type your variables, as shown in the following example: var myInstance:com.macromedia.docs.learnAs2.ClassName = new com.macromedia.docs.learnAs2.ClassName(); You can use the statement to import packages into a script, which lets you use a class’s import abbreviated name rather than its fully qualified name.
  • Page 278 To import a class or package: Open the file called package_test.fla. Type the following code into the Script window: import com.macromedia.utils.*; var a = new ClassA(); // ClassA constructor var b = new ClassB(); // ClassB constructor The previous block of code begins by importing each of the classes within the package by using the wildcard (*) character.
  • Page 279: Assigning A Class To Symbols In Flash

    To create a new instance of the ClassA and ClassB classes: Open the file called package_test.fla. Type the following boldface code into the Script window: import com.macromedia.utils.*; var a:ClassA = new ClassA(); // ClassA constructor a.doSomething(); // call the ClassA's doSomething() method var b:ClassB = new ClassB();...
  • Page 280: Compiling And Exporting Classes

    Select File > New and then select Flash Document to create a new FLA file, and then click OK. Select File > Save As, name the file animal_test.fla, and save the file to the same folder as the Animal.as file you created in step 2. Select Insert >...
  • Page 281 Rename the default layer to content, drag a ProgressBar component from the Components panel to the Stage, and give it an instance name of my_pb. Create a new layer, drag it above the content layer, and rename it actions. Add the following ActionScript code to Frame 1 of the actions layer on the main Timeline: my_pb.indeterminate = true;...
  • Page 282 Select Control > Test Movie to test the Flash document. If the Components load too quickly, select View > Simulate Download from the SWF file. Flash simulates downloading the Flash document at a lower speed, which allows you to see the progress bar component animate as the class files download.
  • Page 283: Understanding Classes And Scope

    To delete ASO files: If you are editing a FLA file, and you want to delete an ASO file, select one of the following in the authoring environment: Select Control > Delete ASO Files to delete ASO files and continue editing. Select Control >...
  • Page 284 To understand scope and external class files: Select File > New and then select ActionScript File, and then click OK. Type or paste the following code into the Script window: Product class Product.as class Product { private var productsXml:XML; // constructor // targetXmlStr - string, contains the path to an XML file function Product(targetXmlStr:String) { /* Create a local reference to the current class.
  • Page 285 Save the previous ActionScript code as Product.as. Create a new Flash document named testProduct.fla in the same directory. Select Frame 1 of the main Timeline. Type the following ActionScript into the Actions panel: var myProduct:Product = new Product("http://www.helpexamples.com/ crossdomain.xml"); Select Control > Test Movie to test this code in the test environment. The contents of the specified XML document appear in the Output panel.
  • Page 286: About Top-Level And Built-In Classes

    Select File > New and then select Flash Document to create a new FLA file, and save the FLA file in the same directory as User.as. Type the following ActionScript code in Frame 1 of the Timeline: trace(User.instances); // 0 var user1:User = new User();...
  • Page 287 Flash provide runtime control over the appearance and behavior of a Flash application. The rest of the built-in ActionScript classes are specific to Macromedia Flash and the Flash Player object model. Examples of these classes are the Camera, MovieClip, and LoadVars classes.
  • Page 288 Other language elements There are other language elements that make up ActionScript, outside of classes. These include directives, constants, global functions, global properties, operators, and statements. For information on how to use each of these language elements, see the following topics: Chapter 5, “Syntax and Language Fundamentals”...
  • Page 289 Class Description Button The Button class provides methods, properties, and event handlers for working with buttons. See Button. Note that the built-in Button class is different from the Button component class, associated with the version 2 component, Button. Camera The Camera class provides access to the user’s camera, if one is installed.
  • Page 290 Class Description LoadVars The LoadVars class lets you transfer variables between a SWF file and a server in name-value pairs. See LoadVars. LocalConnection The LocalConnection class lets you develop SWF files that send instructions to each other without using the method or fscommand() JavaScript.
  • Page 291 Class Description SharedObject The SharedObject class offers persistent local data storage on the client computer, similar to cookies. This class offers real-time data sharing between objects on the client’s computer. See SharedObject. Sound The Sound class provides control over sounds in a SWF file. See Sound.
  • Page 292 Class Description XMLSocket The XMLSocket class lets you create a persistent socket connection between a server computer and client running Flash Player. Client sockets enable low-latency data transfer, such as that which is required for real-time chat applications. See XMLSocket. XMLUI The XMLUI object enables communication with SWF files that are used as a custom user interface for the Flash authoring tool’s...
  • Page 293 The flash.filters package The flash.filters package contains classes for the bitmap filter effects available in Flash Player 8. Filters let you apply rich visual effects, such as blur, bevel, glow, and drop shadows, to Image and MovieClip instances. For more information on each class, see the cross references provided in the following table.
  • Page 294 The flash.geom package The flash.geom package contains geometry classes, such as points, rectangles, and transformation matrices. These classes support the BitmapData class and the bitmap caching feature. For more information on each class, see the cross references provided in the following table.
  • Page 295 The flash.text package The flash.text package contains the TextRenderer class for working with advanced anti- aliasing in available in Flash Player 8. Class Description TextRenderer This class provides functionality for the advanced anti-aliasing capability in Flash Player 8. See TextRenderer (flash.text.TextRenderer).
  • Page 296: About Working With Built-In Classes

    The TextField package contains the StyleSheet class that you can use to apply CSS styles to text. Class Description StyleSheet The StyleSheet class lets you create a style sheet object that contains text formatting rules such as font size, color, and other formatting styles.
  • Page 297 For example, the following code creates a new Sound object: var song_sound:Sound = new Sound(); In some cases, you don’t need to create an instance of a class to use its properties and methods. For more information, see “About class (static) members” on page 298.
  • Page 298 About calling built-in object methods You call an object’s method by using the dot ( ) operator followed by the method. For example, the following code creates a new Sound object and calls its method: setVolume() var my_sound:Sound = new Sound(this); my_sound.setVolume(50);...
  • Page 299 This section describes some of the methodologies for preloading and exporting classes in Flash 8 (including the classes that components in version 2 of the Macromedia Component Architecture use). Preloading involves loading some of the data for a SWF file before the user starts interacting with it.
  • Page 300 To select a different frame for the classes to load into a SWF file: Select File > Publish Settings. Select the Flash tab, and click the Settings button. In the Export Frame for Classes text box, type the number of a new frame to determine when to load the classes.
  • Page 301: Chapter 8: Inheritance

    CHAPTER 8 Inheritance Chapter 7, “Classes,” you learned how to write class files and how classes help you organize code into external files. The chapter also demonstrated how you can organize class files into related packages. This chapter aims to show you how to write more advanced classes that extend the functionality of an existing class.
  • Page 302 Your subclass typically defines additional methods and properties that you can use in your application, hence it extends the superclass. Subclasses can also override (provide their own definitions for) methods inherited from a superclass. If a subclass overrides a method inherited from its superclass, you can no longer access the superclass’s definition within the subclass.
  • Page 303: About Writing Subclasses In Flash

    About writing subclasses in Flash In object-oriented programming, a subclass can inherit the properties and methods of another class, called the superclass. You can extend your own custom classes as well as many of the core and Flash Player ActionScript classes. You cannot extend the TextField class or static classes, such as the Math, Key, and Mouse classes.
  • Page 304 If you don’t place a call to in the constructor function of a subclass, the compiler super() automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. If the superclass doesn’t have a constructor, the compiler creates an empty constructor function and then generates a call to it from the subclass.
  • Page 305 In SubWidget.as, type the following code into the Script window: class SubWidget extends Widget { public function SubWidget() { trace("Creating subwidget #" + Widget.widgetCount); Save your changes to SubWidget.as. Create a new FLA file, and save it as subWidgetTest.fla in the same directory as the previous ActionScript class files.
  • Page 306 Flash generates an error telling you that static members can be accessed only directly through classes. For optimal readability of your code, Macromedia recommends that you always use explicit references to static member variables in your code, as shown in the previous example. Using explicit references means that you can easily identify where the definition of a static member resides.
  • Page 307 Save your changes to the ActionScript document. The Widget class now defines a constructor and a public method called doSomething() Create a new ActionScript file named SubWidget.as and save it in the same directory as Widget.as. If you created the SubWidget class in “Example: Extending the Widget class”...
  • Page 308: Using Polymorphism In An Application

    Open the SubWidget class and add a new method named . Modify your doSomething() class so that it matches the following code (add the code that’s in boldface): class SubWidget extends Widget { public function SubWidget() { trace("Creating subwidget # " + Widget.widgetCount); doSomething();...
  • Page 309 For example, you might start with a class called Mammal that has play() sleep() methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the method from the Mammal class to reflect the habits of those play() particular kinds of animals.
  • Page 310 The previous class defines two private variables, , which are used to _gender _name store the animal’s gender and mammal type. Next, the constructor is defined. The Mammal constructor takes a single parameter, , which it uses to set the private gender _gender variable defined earlier.
  • Page 311 In Dog.as, type the following ActionScript code into the Script window: class Dog extends Mammal { // constructor public function Dog(gender:String) { super(gender); speciesName = "Dog"; public function play():String { return "Fetch a stick."; Notice that the Dog class is very similar in structure to the Cat class, except that a few of the values have changed.
  • Page 312 In mammalTest.fla, type the following ActionScript code into Frame 1 of the main Timeline: var mammals_arr:Array = new Array(); this.createTextField("info_txt", 10, 10, 10, 450, 80); info_txt.html = true; info_txt.multiline = true; info_txt.border = true; info_txt.wordWrap = true; createMammals() createReport() function createMammals():Void { mammals_arr.push(new Dog("Female"));...
  • Page 313: Chapter 9: Interfaces

    CHAPTER 9 Interfaces In object-oriented programming (OOP), an interface is a document that lets you declare (but not define) the methods that must appear within a class. When you work in teams of developers, or build larger applications in Flash, interfaces can be very beneficial during development.
  • Page 314 An interface is not a class; however, this is not altogether true in ActionScript at runtime because an interface is abstract. ActionScript interfaces do exist at runtime to allow type casting (changing an existing data type to a different type). The ActionScript 2.0 object model does not support multiple inheritance.
  • Page 315 For more information on using interfaces, see the following sections: “About the interface keyword” on page 315 “About naming interfaces” on page 315 “Defining and implementing interfaces” on page 316 About the interface keyword keyword defines an interface. An interface is similar to a class, with the interface following important differences: Interfaces contain only declarations of methods, not their implementation.
  • Page 316 Defining and implementing interfaces The process for creating an interface is the same as for creating a class. Like classes, you can define interfaces only in external ActionScript files. At a minimum, the workflow for creating an interface involves the following steps: Defining a interface in an external ActionScript file Saving the interface file to a designated classpath directory (a location where Flash looks for classes) or in the same directory as the application’s FLA file...
  • Page 317 Create a new ActionScript file and save it as MyClass.as in the same directory as the IMyInterface.as. In the MyClass class file, type the following ActionScript code into the Script window: class MyClass { In order to instruct the custom class (MyClass) to use your interface (IMyInterface), you need to use the keyword, which specifies that a class must define all the implements...
  • Page 318: Creating Interfaces As Data Types

    Interface files cannot contain any variable declarations or assignments. Functions that you declare in an interface cannot contain curly braces. For example, the following interface does not compile: interface IBadInterface { // Compiler error. Variable declarations not allowed in interfaces. public var illegalVar:String;...
  • Page 319 In Box.as, type the following ActionScript code into the Script window: class Box implements IMovable { public var xPos:Number; public var yPos:Number; public function Box() { public function moveUp():Void { trace("moving up"); // method definition public function moveDown():Void { trace("moving down"); // method definition Save your changes to the ActionScript document.
  • Page 320: Understanding Inheritance And Interfaces

    This ActionScript code checks whether the instance implements the IMovable newBox interface before you call the method on the object. moveUp() Save the Flash document, and then select Control > Test Movie to test the SWF file. Because the Box instance implements the IMovable interface, the method Box.moveUp() is called, and the text “moving up”...
  • Page 321: Example: Using Interfaces

    In ClassA.as, type the following ActionScript code into the Script window: class ClassA implements Ib { // f1() and f2() are defined in interface Ia. public function f1():Void { public function f2():Void { // f8() and f9() are defined in interface Ib, which extends Ia. public function f8():Void { public function f9():Void { Save your class file and click the Check Syntax button above the Script window.
  • Page 322 In FlashPaper.as, type the following ActionScript code into the Script window: class FlashPaper implements IDocumentation { Save the changes that you made to the ActionScript file. Click the Check Syntax button for your ActionScript class. You see an error that’s similar to the following message: **Error** path\FlashPaper.as: Line 1: The class must implement method 'checkForUpdates' from interface 'IDocumentation'.
  • Page 323: Example: Creating A Complex Interface

    Save your changes to the interface file, and then reopen the FlashPaper.as document. Click the Check Syntax button, and you see a new error message in the Output panel: **Error** path\FlashPaper.as: Line 1: The class must implement method 'addComment' from interface 'IDocumentation'. class FlashPaper implements IDocumentation { Total ActionScript Errors: 1 Reported Errors: 1...
  • Page 324 In Interface.as, type the following ActionScript code into the Script window: // filename: InterfaceA.as interface InterfaceA { public function k():Number; public function n(z:Number):Number; Save the ActionScript document and then create a new ActionScript document named ClassB.as and save it in the complexInterface directory. ClassB.as implements the InterfaceA interface you created previously.
  • Page 325 In ClassC.as, type the following ActionScript code into the Script window: // filename: ClassC.as class ClassC implements InterfaceA { public function k():Number { return 25; // **Error** The class must also implement method 'n' from interface 'InterfaceA'. If you click the Check Syntax button for the ClassC class file, Flash displays an error message in the Output panel that says the current class must implement the method defined in the InterfaceA interface.
  • Page 326 In classdTest.fla, add the following ActionScript code on Frame 1 of the Timeline: // filename: classdTest.fla import ClassD; var myD:ClassD = new ClassD(); trace(myD.k()); // 15 trace(myD.n(7)); // 49 myD.o(); // o Save your changes to the classdTest.fla file and then select Control > Test Movie to test the file.
  • Page 327 In classeTest.fla, type the following ActionScript code on Frame 1 of the Timeline: // filename: classeTest.fla import ClassE; var myE:ClassE = new ClassE(); trace(myE.k()); // 15 trace(myE.n(7)); // 12 myE.o(); // o myE.p(); // p Save the Flash document, and then select Control > Test Movie to test the SWF file. The values , and display in the Output panel.
  • Page 328 Interfaces...
  • Page 329: Chapter 10: Handling Events

    CHAPTER 10 Handling Events Events are actions that occur while a SWF file is playing. An event such as a mouse click or a keypress is called a user event because it occurs as a result of direct user interaction. An event that Flash Player generates automatically, such as the initial appearance of a movie clip on the Stage, is called a system event because it isn’t generated directly by the user.
  • Page 330: Using Event Handler Methods

    For more information on handling events, see the following sections: Using event handler methods ..........330 Using event listeners .
  • Page 331 For example, suppose you have a button named next_btn on the Stage. The following code assigns a function to the button’s event handler; this function advances the playhead onPress to the next frame in the current timeline: next_btn.onPress = function () { nextFrame();...
  • Page 332: Using Event Listeners

    Event handlers for runtime objects You can also assign functions to event handlers for objects you create at runtime. For example, the following code creates a new movie clip instance ( ) and then assigns a function to the clip’s event handler: newclip_mc onPress...
  • Page 333 Stage.width Stage.height is resized. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\StageSize. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/StageSize. Event listener model The event model for event listeners is similar to the model for event handlers (see “Using...
  • Page 334 The code starts with an object, , with a property . Your listener listenerObject eventName object can be any object, such as an existing object, movie clip, or button instance on the Stage, or it can be an instance of any ActionScript class. For example, a custom movie clip could implement the listener methods for Stage listeners.
  • Page 335: Using Event Listeners With Components

    To create an object that listens for focus notification from the Selection class, enter the following code in the Actions panel: // Creates listener object, focusListener. var focusListener:Object = new Object(); // Defines function for listener object. focusListener.onSetFocus = function(oldFocus_txt:TextField, newFocus_txt:TextField) { oldFocus_txt.border = false;...
  • Page 336 Add the following code to Frame 1 of the main Timeline; System.security.allowDomain("http://www.helpexamples.com"); var loaderListener:Object = new Object(); loaderListener.progress = function(evt_obj:Object):Void { trace(evt_obj.type); // progress trace("\t" + evt_obj.target.bytesLoaded + " of " + evt_obj.target.bytesTotal + " bytes loaded"); loaderListener.complete = function(evt_obj:Object):Void { trace(evt_obj.type);...
  • Page 337: Using Button And Movie Clip Event Handlers

    Instead of using a listener object, as in the first procedure under “Using event listeners with components” on page 335, you can use a custom function. The code in the previous example could be rewritten as follows: System.security.allowDomain("http://www.helpexamples.com"); my_ldr.addEventListener("progress", progressListener); my_ldr.addEventListener("complete", completeListener);...
  • Page 338 You can attach only to movie clip instances that have been placed onClipEvent() on() on the Stage during authoring. You cannot attach to movie clip onClipEvent() on() instances that are created at runtime (using the method, for example). To attachMovie() attach event handlers to objects created at runtime, use event handler methods or event listeners.
  • Page 339 To use an on handler and onPress event handler: Create a new Flash document and save it as handlers.fla. Select the Rectangle Tool and draw a large square on the Stage. Select the Selection Tool, double-click the square on the Stage, and press F8 to launch the Convert to Symbol dialog box.
  • Page 340 Specifying events for on or onClipEvent methods To use an handler, attach it directly to an instance of a button or on() onClipEvent() movie clip on the Stage and specify the event you want to handle for that instance. For a complete list of events supported by the event handlers, see on()
  • Page 341 Attaching or assigning multiple handlers to one object You can also attach more than one handler to an object if you want different scripts to run when different events occur. For example, you could attach the following onClipEvent() handlers to the same movie clip instance. The first executes when the movie clip first loads (or appears on the Stage);...
  • Page 342: Broadcasting Events From Component Instances

    Select Control > Test Movie to test the document. The image loads into the instance, and the event img_mc onPress() onRelease() handlers let you drag the image around the Stage. Broadcasting events from component instances For any component instance, you can specify how an event is handled. Component events are handled differently than events broadcast from native ActionScript objects.
  • Page 343: Event Handler Scope

    Rename the new layer actions and add the following ActionScript to Frame 1 of the movie clip’s timeline: stop(); Select Frame 10, all three layers, and select Insert > Timeline > Keyframe. Add a action on Frame 10 of the actions layer, and add a frame label of _over in stop() frame 10 of the labels layer.
  • Page 344 For example, consider the following two event handlers. The first is an event handler onPress associated with a movie clip named . The second is an handler attached to the clip_mc on() same movie clip instance. // Attached to clip_mc's parent clip timeline: clip_mc.onPress = function () { var shoeColor;...
  • Page 345 Within an event handler or event listener definition, the same function applies to the play() timeline that contains the function definition. For example, suppose you declare the following event handler method on the timeline that contains the movie my_mc.onPress my_mc clip instance: // Function defined on a timeline my_mc.onPress = function () {...
  • Page 346 This code cannot work correctly because there is a problem involving scope with the event handlers, and what refers to is confused between the event handler and the class. this onLoad The behavior that you might expect in this example is that the method onLoadVarsDone() will be invoked in the scope of the TextLoader object;...
  • Page 347: Scope Of The This Keyword

    Scope of the this keyword keyword refers to the object in the currently executing scope. Depending on what this type of event handler technique you use, can refer to different objects. this Within an event handler or event listener function refers to the object that defines the this event handler or event listener method.
  • Page 348 To use the Delegate class to listen for events: Create a new Flash document and save it as delegate.fla. Drag a Button component from the User Interface folder of the Components panel to the library. You add and position the button instance on the Stage using ActionScript in a later step. Add the following ActionScript to Frame 1 of the main Timeline: import mx.controls.Button;...
  • Page 349 The remaining three sections of code each create a new Button component instance on the Stage, reposition the instance, and add an event listener for the event. The first click button adds an event listener for the event and passes a reference to a click click handler function directly.
  • Page 350 Handling Events...
  • Page 351: Chapter 11: Working With Movie Clips

    In this way, movie clips provide the foundation of component-based architecture in Macromedia Flash Basic 8 and Macromedia Flash Professional 8. In fact, the components available in the Components panel (Window > Components) are sophisticated movie clips that are designed and programmed to look and behave in certain ways.
  • Page 352: About Controlling Movie Clips With Actionscript

    For more information on movie clips, see the following topics: About controlling movie clips with ActionScript ......352 Calling multiple methods on a single movie clip .
  • Page 353 For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 354: Calling Multiple Methods On A Single Movie Clip

    SWF file, which includes scripted animation. You can find the sample source files, gallery_tree.fla and gallery_tween.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.
  • Page 355: Loading And Unloading Swf Files

    Loading and unloading SWF files To play additional SWF files without closing Flash Player, or to switch SWF files without loading another HTML page, you can use one of the following options: The global function or method of the MovieClip class. loadMovie() loadMovie() method of the MovieClipLoader class.
  • Page 356 Specifying a root timeline for loaded SWF files ActionScript property specifies or contains a reference to the root timeline of a _root SWF file. If a SWF file has multiple levels, the root timeline is on the level that contains the currently executing script.
  • Page 357: Changing Movie Clip Position And Appearance

    This step ensures that any references to in contents.swf—or any SWF file loaded into _root —refers to its own timeline, not to the actual root timeline of container.swf. Now target_mc when you click the button, " " appears. Alternatively, the author of contents.swf could add the following code to its main timeline: // Added to Frame 1 in contents.swf: this._lockroot = true;...
  • Page 358 For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 359: Dragging Movie Clips

    On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. Dragging movie clips You can use the global function or the method to startDrag() MovieClip.startDrag() make a movie clip draggable. For example, you can make a draggable movie clip for games, drag-and-drop functions, customizable interfaces, scroll bars, and sliders.
  • Page 360: Creating Movie Clips At Runtime

    SWF file, which includes creating movie clips at runtime. You can find the sample source file, gallery_tween.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.
  • Page 361 For an example source file that creates and removes numerous movie clips at runtime, you can find a sample source file, animation.fla, in the Samples folder on your hard disk In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation.
  • Page 362 For an example source file that creates and removes numerous movie clips at runtime, you can find a sample source file, animation.fla, in the Samples folder on your hard disk In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation.
  • Page 363 In the Library panel, select Linkage from the Library panel pop-up menu. The Linkage Properties dialog box appears. For Linkage, select Export for ActionScript. For Identifier, enter an ID for the movie clip. By default, the identifier is the same as the symbol name. You can optionally assign an ActionScript class to the movie clip symbol.
  • Page 364: Adding Parameters To Dynamically Created Movie Clips

    For more information, see attachMovie ( in the MovieClip.attachMovie method) ActionScript 2.0 Language Reference. Adding parameters to dynamically created movie clips When you use to create or MovieClip.attachMovie() MovieClip.duplicateMovie() duplicate a movie clip dynamically, you can populate the movie clip with parameters from another object.
  • Page 365 SWF file, which includes creating movie clips at runtime. You can find the sample source file, gallery_tween.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.
  • Page 366: Managing Movie Clip Depths

    Managing movie clip depths Every movie clip has its own z-order space that determines how objects overlap within its parent SWF file or movie clip. Every movie clip has an associated depth value, which determines if it renders in front of or behind other movie clips in the same movie clip timeline.
  • Page 367 Determining the next highest available depth To determine the next highest available depth within a movie clip, use . The integer value returned by this method indicates MovieClip.getNextHighestDepth() the next available depth that will render in front of all other objects in the movie clip. The following code attaches a new movie clip, with a depth value of 10, on the root timeline named .
  • Page 368 Determining the depth of an instance To determine the depth of a movie clip instance, use MovieClip.getDepth() The following code iterates over all the movie clips on a SWF file’s main timeline and shows each clip’s instance name and depth value in the Output panel: for (var item:String in _root) { var obj:Object = _root[item];...
  • Page 369: About Caching And Scrolling Movie Clips With Actionscript

    Select Control > Test Movie to test the document. When you click the instances on the Stage, they swap depths. You’ll see the two instances change which clip is on top of the other clip. For more information, see in the swapDepths (MovieClip.swapDepths method) ActionScript 2.0 Language Reference.
  • Page 370 You can find a sample source file that shows you how bitmap caching can be applied to an instance. Find the file called cacheBitmap.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.
  • Page 371 On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap. You can also find a sample source file that shows you how to apply bitmap caching to scrolling text. Find the sample source file, flashtype.fla, in the Samples folder on your hard disk.
  • Page 372 You can find a sample source file that shows you how bitmap caching can be applied to an instance. Find the file called cacheBitmap.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.
  • Page 373 Create or import a complex vector graphic into the FLA file. You can find a complex vector graphic in the finished source file for this example in the following directory: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/ Samples and Tutorials/Samples/ActionScript/CacheBitmap.
  • Page 374 Select Frame 1 of the Timeline, and then add the following ActionScript to the Actions panel: import mx.transitions.Tween; var star_array:Array = new Array(); for (var i:Number = 0; i < 20; i++) { makeStar(); function makeStar():Void { var depth:Number = this.getNextHighestDepth(); var star_mc:MovieClip = this.attachMovie("star_id", "star"...
  • Page 375 You can find a sample source file that shows you how bitmap caching can be applied to an instance. Find the file called cacheBitmap.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.
  • Page 376: Using Movie Clips As Masks

    Select the instance on the Stage, and then type my_mc into the Instance Name text box in the Property inspector. Select Frame 1 of the Timeline, and then type the following code into the Actions panel: /* When you set cacheAsBitmap, the internal bitmap is opaque and renders faster.
  • Page 377 To see an example of alpha masking, download the alpha masking sample file from www.macromedia.com/go/flash_samples. In this sample file, the mask is an oval ( ) that has alpha of 50% and a blur filter oval_mask applied to it.
  • Page 378: Handling Movie Clip Events

    In the Actions panel, the following code is placed on Frame 1 of the Timeline: flower_maskee.setMask(oval_mask); When you test the document (Control > Test Movie), the maskee is alpha blended by using the mask. Mask layers do not support alpha channel masking. You must use ActionScript code to apply a mask, and use runtime bitmap caching.
  • Page 379: Initializing Class Properties

    Enter the following code in your script file: // MoveRight class -- moves clip to the right 20 pixels when clicked class MoveRight extends MovieClip { public function onPress() { this._x += 20; Save the document as MoveRight.as in the BallTest directory. To assign the class to a movie clip symbol: In Flash, select File >...
  • Page 380 For example, the following class named MoveRightDistance is a variation of the MoveRight class (see “Assigning a class to a movie clip symbol” on page 378). The difference is a new property named , whose value determines how many pixels a movie clip moves each distance time it is clicked.
  • Page 381: Chapter 12: Working With Text And Strings

    Many of the applications, presentations, and graphics that you create with Macromedia Flash Professional 8 or Macromedia Flash Basic 8 include some kind of text. You can use many different kinds of text. You might use static text in your layouts, but dynamic text for longer passages of text.
  • Page 382 Device fonts Device fonts are special fonts in Flash that are not embedded in a SWF file. Instead, Flash Player uses whatever font on the local computer that most closely resembles the device font. Because font outlines are not embedded, a SWF file size is smaller than using embedded font outlines.
  • Page 383: About Text Fields

    About text fields A dynamic or input text field is a TextField object (an instance of the TextField class). When you create a text field in the authoring environment, you can assign it an instance name in the Property inspector. You can use the instance name in ActionScript statements to set, change, and format the text field and its content by using the TextField and TextFormat classes.
  • Page 384: Using The Textfield Class

    You can find sample source files that demonstrate how to work with text fields using ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. Working with Text and Strings...
  • Page 385 Or, if you entered a value in the variable text field in the Property inspector, you can assign a value to the text field by creating a variable with the specified name. If you use version 2 of Macromedia Components Architecture in your Flash document, you can also assign values by creating bindings between components.
  • Page 386 ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.
  • Page 387 ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.
  • Page 388 ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.
  • Page 389 ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.
  • Page 390 ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.
  • Page 391 You can find sample source files that demonstrate how to work with text fields using ActionScript. The source files are called textfieldsA.fla and textfieldsB.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. About text fields...
  • Page 392: About Loading Text And Variables Into Text Fields

    On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. About loading text and variables into text fields You can load text into a Flash document several ways, including (but certainly not limited to) using FlashVars, LoadVars, XML, or web services. Perhaps the simplest method of passing text...
  • Page 393 ActionScript. The source files are called loadText.fla and formattedText.fla, and you can find them in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText.
  • Page 394 <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="flashvars.swf" FlashVars="username=Thomas" quality="high" bgcolor="#ffffff" width="550" height="400" name="flashvars" align="middle" allowScriptAccess="sameDomain" type="application/x- shockwave-flash" pluginspage="http://www.macromedia.com/go/ getflashplayer" /> </object> Save your changes to the HTML document. Open the modified HTML in a web browser. The SWF file displays the name “Thomas” in the dynamically created text field on the Stage.
  • Page 395 To use LoadVars to populate a text field with external text: Create a new Flash document and save it as loadvarsText.fla. Add the following ActionScript to Frame 1 of the Timeline: this.createTextField("my_txt", 10, 10, 10, 320, 100); my_txt.autoSize = "left"; my_txt.border = true;...
  • Page 396 Loading variables by using LoadVars The LoadVars class also lets you load variables in a URL-encoded format, similar to passing variables in the query string in a web browser. The following example demonstrates how to load a remote text file into a SWF file and display its variables, monthNames dayNames To load variables from a text file by using LoadVars:...
  • Page 397 Loading and displaying text from an XML document XML data is a popular way to distribute content on the Internet, in part because it is a widely accepted standard for organizing and parsing data. As such, XML is an excellent choice for sending and receiving data from Flash;...
  • Page 398: Using Fonts

    Using fonts Fonts are sets of characters with a similar font face, style, and size. No matter what you create using Flash Basic 8 or Flash Professional 8, you will probably use text with at least one or two fonts in your Flash applications. If you build animations, and you are not sure if your end users will have a specific font installed on their systems, you need to understand the basics about embedding fonts.
  • Page 399 Don’t Embed clears any previously specified individual characters or character sets. Clicking Don’t Embed in the Character Embedding dialog box removes any specified embedded characters and character sets that were previously chosen without asking you to confirm. Embedding characters If you’re working with embedded fonts and know exactly what characters you need, you can reduce file size by embedding only the characters that you need instead of including additional, unused font outlines.
  • Page 400 You will see the string “helo wrd”. Instead of having to tell Flash which characters you want to include, Flash can determine all unique characters in the specified text field for you. Flash can determine characters to embed automatically only if the text field contains text on the Stage.
  • Page 401 Select the text field, and open the Property inspector. Set the text field to single-line. Select the name of the embedded font by using the Font drop-down menu. Embedded fonts have an asterisk (*) after the font name. Click Embed in the Property inspector to launch the Character Embedding dialog box. The Character Embedding dialog box lets you select the individual characters or character sets that you want to embed for the selected text field.
  • Page 402 To create a custom character set, you must edit the UnicodeTable.xml file, located in the C:\Program Files\Macromedia\Flash 8\<language>\First Run\FontEmbedding\ directory. This file defines the default character sets and the character ranges and characters that they contain.
  • Page 403 Before you edit this file, you should make a backup copy in case you want to revert to the original Unicode table. Macromedia recommends that you do not modify the existing character sets that are installed with Flash, and that you instead make your own custom character sets that include the characters and punctuation that you require.
  • Page 404 Add a new TextField instance on the Stage by using the Text tool. Set the Text type of the TextField to Dynamic in the Property inspector, and then click Embed Character Options to open the Character Embedding dialog box. Scroll to the bottom of the Character Embedding dialog box and select your new custom character set, Uppercase and Numerals [A..Z,0..9] (38 glyphs).
  • Page 405 Click OK. In the library, right-click the font symbol, and then select Linkage from the context menu. Flash opens the Linkage Properties dialog box. Select the Export for ActionScript and Export in first frame options and click OK. Add the following ActionScript to Frame 1 of the Timeline: // 1 this.createTextField("thickness_txt", 10, 0, 0, Stage.width, 22);...
  • Page 406: About Font Rendering And Anti-Alias Text

    Save your changes to the FLA file. Select Control > Test Movie to test your Flash document. When you move the mouse pointer to the left half of the Stage, the font thickness decreases. When you move the mouse pointer to the right half of the Stage, the font thickness increases.
  • Page 407 You can find the sample source file, flashtype.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. About font rendering and anti-alias text...
  • Page 408 Font rendering options in Flash Five different font rendering options are available in Flash 8. To select an option, select the text field and open the Property inspector. Select an option from the Font rendering method pop-up menu. Device Fonts Produces a smaller SWF file size.
  • Page 409 Flash Player 8. Advanced anti-aliasing allows font faces to be rendered at very high quality at small sizes. It is best used with applications that have a lot of small text. Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points.
  • Page 410 Select the Export for ActionScript and Export in First Frame options, enter the linkage identifier Arial-10, and click OK. Add the following ActionScript to Frame 1 of the main Timeline: var text_fmt:TextFormat = new TextFormat(); text_fmt.font = "Arial-10"; text_fmt.size = 10; this.createTextField("my_txt", 10, 20, 20, 320, 240);...
  • Page 411 Advanced anti-aliasing allows font faces to be rendered at high quality at small sizes. It is best used with applications that have a lot of small text. Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points.
  • Page 412 Adjusting the outside and inside cutoff values affects stroke weight and edge sharpness. The spacing between these two parameters is comparable to twice the filter radius of classic anti- aliasing methods; a narrow spacing provides a sharper edge, while a wider spacing provides a softer, more filtered edge.
  • Page 413 Select Frame 1 of the main Timeline, and add the following ActionScript in the Actions panel: import flash.text.TextRenderer; var arialTable:Array = new Array(); arialTable.push({fontSize:16.0, insideCutoff:0.516, outsideCutoff:0.416}); arialTable.push({fontSize:32.0, insideCutoff:2.8, outsideCutoff:-2.8}); TextRenderer.setAdvancedAntialiasingTable("Arial", "bolditalic", "dark", arialTable); var my_fmt:TextFormat = new TextFormat(); my_fmt.align = "justify"; my_fmt.font = "Arial-embedded";...
  • Page 414: About Text Layout And Formatting

    After the text loads from the remote server, Flash displays some text in the text field, and you can see the advanced anti-aliasing table properties applied to your text field. The embedded font on the Stage should appear like it has a slight blur effect because of the current values.
  • Page 415 To modify a text field’s sharpness and thickness: Create a new Flash document and save it as sharpness.fla. Select New Font from the pop-up menu in the upper-right corner of the Library panel. Select Arial from the Font drop-down menu and set the font size to 24 points. Enter the font name of Arial-24 (embedded) in the Name text box and click OK.
  • Page 416 You can find the sample source file, flashtype.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. Working with Text and Strings...
  • Page 417 Using a grid fit type When you use advanced anti-aliasing on a text field, three types of grid fitting are available: none Specifies no grid fitting. Horizontal and vertical lines in the glyphs are not forced to the pixel grid. This setting is usually good for animation and for large font sizes. pixel Specifies that strong horizontal and vertical lines are fit to the pixel grid.
  • Page 418 Add the following code to Frame 1 of the main Timeline: var my_fmt:TextFormat = new TextFormat(); my_fmt.size = 10; my_fmt.font = "Arial-10"; var h:Number = Math.floor(Stage.height / 3); this.createTextField("none_txt", 10, 0, 0, Stage.width, h); none_txt.antiAliasType = "advanced"; none_txt.embedFonts = true; none_txt.gridFitType = "none";...
  • Page 419 The preceding ActionScript code can be separated into five sections. The first section defines a new text format object that specifies two properties, . The size font font property refers to the linkage identifier of the font symbol currently in the document library.
  • Page 420 To format a text field with the TextFormat class: In a new Flash document, create a text field on the Stage using the Text tool. Type some text in the text field on the Stage, such as Bold, italic, 24 point text. In the Property inspector, type myText_txt in the Instance Name text box, select Dynamic from the Text Type pop-up menu, and select Multiline from the Line Type pop-up menu.
  • Page 421: Formatting Text With Cascading Style Sheet Styles

    Default properties of new text fields Text fields created at runtime with receive a default TextFormat object createTextField() with the following properties: align = "left" blockIndent = 0 bold = false bullet = false color = 0x000000 font = "Times New Roman" (default font is Times on Mac OS X) indent = 0 italic = false kerning = false...
  • Page 422 CSS formatting to text that you load into a SWF file at runtime. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. Working with Text and Strings...
  • Page 423 Supported CSS properties Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/ TR/REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name;...
  • Page 424: Creating A Style Sheet Object

    In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. Loading external CSS files You can define styles in an external CSS file and then load that file into a style sheet object.
  • Page 425 In the following example, you create and load an external CSS file and use the method to retrieve the names of the TextField.StyleSheet.getStyleNames() loaded styles. To load an external style sheet: In your preferred text or CSS editor, create a new file. Add the following style definitions to the file: .bodyText { font-family: Arial,Helvetica,sans-serif;...
  • Page 426 CSS formatting to text that you load into a SWF file at runtime. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. Creating new styles with ActionScript You can create new text styles with ActionScript by using the...
  • Page 427 Applying styles to a TextField object To apply a style sheet object to a TextField object, you assign the style sheet object to the text field’s property. styleSheet textObj_txt.styleSheet = styles; Do not confuse the property with the TextField.StyleSheet class. TextField.styleSheet The capitalization indicates the difference.
  • Page 428 Add the following ActionScript to Frame 1 of the main Timeline: // Create a new style sheet object and set styles for it. var styles:TextField.StyleSheet = new TextField.StyleSheet(); styles.setStyle("html", {fontFamily:'Arial,Helvetica,sans-serif', fontSize:'12px', color:'#0000FF'}); styles.setStyle("body", {color:'#00CCFF', textDecoration:'underline'}); styles.setStyle("h1",{fontFamily:'Arial,Helvetica,sans-serif', fontSize:'24px', color:'#006600'}); /* Assign the style sheet object to myTextArea component. Set html property to true, set styleSheet property to the style sheet object.
  • Page 429 Combining styles CSS styles in Flash Player are additive; that is, when styles are nested, each level of nesting can contribute style information, which is added together to result in the final formatting. The following example shows some XML data assigned to a text field: <sectionHeading>This is a section</sectionHeading>...
  • Page 430 Styling built-in HTML tags Flash Player supports a subset of HTML tags. (For more information, see “Using HTML- formatted text” on page 436.) You can assign a CSS style to every instance of a built-in HTML tag that appears in a text field. For example, the following code defines a style for the built-in HTML tag.
  • Page 431 An example of using styles with HTML This section presents an example of using styles with HTML tags. You can create a style sheet that styles some built-in tags and defines some style classes. Then, you can apply that style sheet to a TextField object that contains HTML-formatted text.
  • Page 432 Create a new text file in a text or HTML editor, and save the document as myText.htm. Add the following text to the file: <p class='headline'>Flash adds FlashType rendering technology!</ p><p><span class='byline'>San Francisco, CA</span>--Macromedia Inc. announced today a new version of Flash that features a brand new font rendering technology called FlashType, most excellent at rendering small text with incredible clarity and consistency across platforms.
  • Page 433 } else { trace("Unable to load CSS file."); styles.load(css_url); In this ActionScript, you are loading the text from an external file. For information on loading external data, see Chapter 15, “Working with Images, Sound, and Video.” Save the file as news_html.fla in the same directory that contains the CSS file you created in step 3.
  • Page 434 An example of using styles with XML In this section, you create a FLA file that has XML-formatted text. You’ll create a style sheet using ActionScript, rather than importing styles from a CSS file as shown in “An example of using styles with HTML”...
  • Page 435 To create the XML text to assign to the text field, open a text editor and enter the following text into a new document: <story><title>Flash now has FlashType</title><mainBody><byline>San Francisco, CA</byline>--Macromedia Inc. announced today a new version of Flash that features the new FlashType rendering technology. For more information, visit the <a href="http:// www.macromedia.com">Macromedia Flash website</a></mainBody></story>...
  • Page 436: Using Html-Formatted Text

    Using HTML-formatted text Flash Player supports a subset of standard HTML tags such as that you can use <p> <li> to style text in any dynamic or input text field. Text fields in Flash Player 7 and later also support the tag, which lets you embed image files (JPEG, GIF, PNG), SWF files, and <img>...
  • Page 437 To render HTML correctly, you must use the correct syntax. Attributes of HTML tags must be enclosed in double (") or single (') quotation marks. Attribute values without quotation marks can produce unexpected results, such as improper rendering of text. For example, the following HTML snippet cannot be rendered properly by Flash Player because the value assigned to the attribute (...
  • Page 438 _top For example, the following HTML code creates the link “Go home,” which opens www.macromedia.com in a new browser window: urlText_txt.htmlText = "<a href='http://www.macromedia.com' target='_blank'>Go home</a>"; You can use the special...
  • Page 439 Font tag tag specifies a font or list of fonts to display the text. <font> The font tag supports the following attributes: Only hexadecimal color ( ) values are supported. For example, the color #FFFFFF following HTML code creates red text: myText_txt.htmlText = "<font color='#FF0000'>This is red text</font>";...
  • Page 440 tag supports the following attributes: <img> Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, and SWF files) do not show until they are downloaded completely.
  • Page 441 Apples Oranges Lemons Ordered and unordered lists ( tags) are not recognized by Flash Player, <ol> <ul> so they do not modify how your list is rendered. All list items use bullets. Paragraph tag tag creates a new paragraph. You must set the text field to be a multiline text field to <p>...
  • Page 442 Text format tag tag lets you use a subset of paragraph formatting properties of the <textformat> TextFormat class within HTML text fields, including line leading, indentation, margins, and tab stops. You can combine tags with the built-in HTML tags. <textformat> tag has the following attributes: <textformat>...
  • Page 443 To create a formatted table of data using tab stops: Create a new Flash document, and save it as tabstops.fla. In the Timeline, select the first frame on Layer 1. Open the Actions panel (Window > Actions), and enter the following code in the Actions panel: // Create a new text field.
  • Page 444 About supported HTML entities HTML entities help you display certain characters in HTML formatted text fields, so that they are not interpreted as HTML. For example, you use less-than ( ) and greater-than ( < > characters to enclose HTML tags, such as .
  • Page 445 About embedding images, SWF files, and movie clips in text fields In Flash Player 7 and later, you can use the tag to embed image files (JPEG, GIF, <img> PNG), SWF files, and movie clips inside dynamic and input text fields, and TextArea component instances.
  • Page 446 Save the document and select Control > Test Movie to test the document. The upper text field should have a sentence of text and most likely an error message in the Output panel saying that Flash was unable to locate a file named beach.gif in the current directory.
  • Page 447 Select Control > Test Movie to test the Flash document. About specifying height and width values If you specify attributes for an tag, space is reserved in the text field width height <img> for the image file, SWF file, or movie clip. After an image or SWF file is downloaded completely, it appears in the reserved space.
  • Page 448 Click a blank frame between Frame 1 and 20, and set the tween type to Shape in the Property inspector. Save the current document as animation.fla. Select Control > Test Movie to preview the animation. The SWF file is created in the same directory as the FLA. For this exercise to work correctly, you need the SWF file to generate so that you can load it into a separate FLA file.
  • Page 449: Example: Creating Scrolling Text

    About making hypertext links out of embedded media To make a hypertext link out of an embedded image file, SWF file, or movie clip, enclose the tag in an tag: <img> <a> textField_txt.htmlText = "Click the image to return home<a href='home.htm'><img src='home.jpg'></a>";...
  • Page 450: About Strings And The String Class

    To use the scroll property to create scrolling text: Do one of the following: Use the Text tool to drag a text field on the Stage. Assign the text field the instance name textField_txt in the Property inspector. Use ActionScript to create a text field dynamically with the method.
  • Page 451 You can associate each character with a specified character code, which you can also optionally use to display text. For example, the character “A” is represented by the Unicode character code 0041, or 65 in ASCII (American Standard Code for Information Interchange). For more information on character codes and code charts, see www.unicode.org/charts.
  • Page 452 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 453 Using the Locale class The Locale class (mx.lang.Locale) allows you to control how multilanguage text is displayed in a Flash application at runtime. With the Strings panel, you can use string IDs instead of string literals in dynamic text fields, which allows you to create a SWF file that displays text loaded from a language-specific XML file.
  • Page 454 Type the string bonjour in the fr column. You use these strings when you use the combo box to change the language on lang_cb the Stage. Add the following ActionScript to Frame 1 of the main Timeline: import mx.lang.Locale; Locale.setLoadCallback(localeListener); lang_cb.dataProvider = Locale.languageCodeArray.sort();...
  • Page 455 For more information, see in the ActionScript 2.0 Language Locale (mx.lang.Locale) Reference. Using an input method editor An input method editor (IME) lets users type non-ASCII text characters in Asian languages such as Chinese, Japanese, and Korean. The IME class in ActionScript lets you directly manipulate the operating system’s IME in the Flash Player application that is running on a client computer.
  • Page 456 Select Control > Test Movie to test the document. A message appears in the Output panel stating whether you have an IME installed and currently active. You can also use the IME class to enable and disable the IME in Flash at runtime. The following example requires that you have an IME installed on your system.
  • Page 457 return false; } else { trace("Please install an IME and try again."); return false; The preceding code is separated into five sections. The first section calls the checkIME() method, which displays a message in the Output panel if the system has an IME installed or active.
  • Page 458 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 459 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 460 Every string has a property, which is equal to the number of characters in the string: length var companyStr:String = "macromedia"; trace(companyStr.length); // 10 An empty string and a null string both have a length of zero: var firstStr:String = new String();...
  • Page 461 If a string doesn’t contain a value, its length is set to undefined: var thirdStr:String; trace(thirdStr.length); // undefined If your string contains a null byte character (\0), the string value will be truncated. You can also use character codes to define a string. For more information on character codes and character encoding, see “About strings and the String class”...
  • Page 462 Modify the existing ActionScript code so that it traces the ASCII value for each character: var myStr:String = "hello world!"; for (var i:Number = 0; i < myStr.length; i++) { trace(myStr.charAt(i) + " - ASCII=" + myStr.charCodeAt(i)); Save the current Flash document and select Control > Test Movie to preview the SWF file. When you run this code, the following is displayed in the Output panel: h - ASCII=104 e - ASCII=101...
  • Page 463 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 464 Converting and concatenating strings You can use the method to convert many objects to strings. Most built-in objects toString() have a method for this purpose: toString() var n:Number = 0.470; trace(typeof(n.toString())); // string When you use the addition ( ) operator with a combination of string and nonstring instances, you don’t need to use the method.
  • Page 465 The preceding code shows two methods of concatenating strings. The first method uses the addition (+) operator to join the string with the string . The second str1 "ish" method uses the addition and assignment (+=) operator to concatenate the string "ish"...
  • Page 466 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 467 Returning substrings methods of the String class are similar. Both return a substr() substring() substring of a string and both take two parameters. In both methods, the first parameter is the position of the starting character in the given string. However, in the method, the substr() second parameter is the length of the substring to return, and in the...
  • Page 468 You can find a sample source file, strings.fla, in the Samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings.
  • Page 469: Chapter 13: Animation, Filters, And Drawings

    Animation, Filters, and Drawings This chapter describes how to add animation to your Macromedia Flash Basic 8 and Macromedia Flash Professional 8 applications using ActionScript instead of (or in addition to) timeline-based animations that use motion or shape tweens. Using code to create animation and effects often reduces the file size of your finished application, and can also improve the performance and consistency of the animation itself.
  • Page 470: Scripting Animation With Actionscript 2.0

    For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 471 About animation and frame rate When you add animation to an application, consider the frame rate that you set your FLA file to. You need to think about frame rate when working with animations because it can affect the performance of your SWF file and the computer that plays it. Setting a frame rate too high can lead to processor problems, especially when you use many assets or use ActionScript to create animation.
  • Page 472 Fading objects with code When you work with movie clips on the Stage, you might want to fade the movie clip in or out instead of toggling its property. The following procedure demonstrates how to _visible use an event handler to animate a movie clip. onEnterFrame To fade a movie clip by using code: Create a new Flash document called fade1.fla.
  • Page 473 For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 474 Adding color and brightness effects with code In addition to using ActionScript to set and animate alpha fades (see “Fading objects with code” on page 472), you can animate various color and brightness effects by using code instead of using the Filters panel in the Property inspector. The following procedure loads a JPEG image and applies a color transform filter, which modifies the red and green channels as the mouse pointer moves along the x-axis and y-axis.
  • Page 475 To use the ColorMatrixFilter class to change an image to a grayscale image: Create a new Flash document called grayscale.fla. Select Frame 1 of the Timeline, and add the following code to the Actions panel: import flash.filters.ColorMatrixFilter; System.security.allowDomain("http://www.helpexamples.com"); var mcl_obj:Object = new Object(); mcl_obj.onLoadInit = function(target_mc:MovieClip):Void { var myElements_array:Array = [0.3, 0.59, 0.11, 0, 0, 0.3, 0.59, 0.11, 0, 0,...
  • Page 476 For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 477 On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. Moving objects with code Using ActionScript to move an object is similar to modifying an object’s property, _alpha except that you instead modify the object’s property. The following procedure animates a dynamically loaded JPEG image and slides it horizontally across the Stage.
  • Page 478 For an example of scripted animation in Flash, you can find a sample source file, animation.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.
  • Page 479 To pan an instance on the Stage using code: Create a new Flash document called pan.fla. Change the frame rate of the document to 24 fps in the Property inspector. The animation is much smoother if you use a higher frame rate, such as 24 fps. Select Frame 1 of the Timeline, and add the following code to the Actions panel: System.security.allowDomain("http://www.helpexamples.com/");...
  • Page 480: About Bitmap Caching, Scrolling, And Performance

    The first section of code in this code example defines two variables: direction . The variable controls whether the masked image scrolls from left to speed direction right ( ) or right to left ( ). The variable controls how many pixels are moved each speed time the event handler is called.
  • Page 481: About The Tween And Transitionmanager Classes

    When you install Flash Basic 8 or Flash Professional 8, you also install two powerful classes: the Tween and TransitionManager classes. This section describes how to use these classes with movie clips and Macromedia V2 components (included with Flash MX 2004 and Flash 8) to add animation easily to your SWF files.
  • Page 482 Flash Basic 8 or Flash Professional 8. For example, you can use the classes with the component set of version 2 of the Macromedia Component Architecture, or with movie clips. If you want to change the way a ComboBox component animates, you can use the TransitionManager class to add some easing when the menu opens.
  • Page 483 Adding tweens and transitions to a file in Flash Professional 8 (Flash Professional 8 only) This section describes adding tweens and transitions to a Flash Professional slide presentation to demonstrate what they look like for Flash Professional users. However, you can add transitions and tweens to your Flash Basic 8 (or Flash Professional 8) applications if you use code.
  • Page 484 This code calls the TransitionManager class and then applies the Zoom transition with the specified easing method. In this case, the mx.transitions.easing.Bounce.easeOut transition applies to the selected slide. To apply this effect to a movie clip, you can modify the ActionScript to use in your Flash animations. Modifying the code to work with a movie clip symbol is easy: change the first parameter from to the eventObj.target...
  • Page 485 To preview how each transition works with the different methods in the easing classes, you can double-click Transition.swf in boot drive\Program Files\Macromedia\Flash 8\language\First Run\Behaviors\ folder or Macintosh HD:Applications:Macromedia Flash 8:First Run:Behaviors: to open the SWF file in the stand-alone player.
  • Page 486 With the image still selected, open the Property inspector (Window > Properties > Properties), and assign the movie clip the instance name img1_mc. Select Frame 1 of the main Timeline and add the following ActionScript to the Actions panel: mx.transitions.TransitionManager.start(img1_mc, {type:mx.transitions.Zoom, direction:0, duration:1, easing:mx.transitions.easing.Bounce.easeOut, param1:empty, param2:empty});...
  • Page 487 You can find a sample source file that uses these classes to add scripted animation. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 488 Provides the easing effect at the beginning and end of the transition. easeInOut To open these classes in Flash or your ActionScript editor, browse to Hard Disk\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing\ folder on Windows (assumes a default installation), or :Applications:Macromedia Flash Macintosh HD 8:First Run:Classes:mx:transitions:easing.
  • Page 489 You can find a sample source file that adds scripted animation using these classes. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 490 You can find a sample source file that adds scripted animation using these classes. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 491 In this case, the package resides in the C:\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing folder (Windows), or HD:Applications:Macromedia Flash 8:First Run:Classes:mx:transitions:easing (Macintosh). You might agree that importing an entire package is much better than having to import the six classes separately. Instead of referring to the mx.transitions.Tween class, your ActionScript directly refers to the Tween class.
  • Page 492 Instead of using seconds, you can fade the symbol over a few frames. To set the duration in frames instead of seconds in the Tween class, you change the final parameter, useSeconds from . When you set the parameter to , you tell Flash that the specified true false...
  • Page 493 To trigger code when an animation is completed: Create a new document, and call it triggerTween.fla. Create a movie clip on the Stage. Select the movie clip instance and type ball_mc into the Instance Name text box in the Property inspector. Select Frame 1 of the Timeline and add the following code in the Actions panel: import mx.transitions.Tween;...
  • Page 494 After the initial tween finishes, the movie clip tweens back to its original position at ball_mc 0 pixels. The following snippet (edited for brevity) shows the function prototype for the method: continueTo() function continueTo(finish:Number, duration:Number):Void { /* omitted to save space. */ Only two arguments pass to the method, instead of the seven arguments for continueTo()
  • Page 495 To create an animation that continues endlessly: Create a new Flash document called yoyo.fla. Open the Actions panel and enter the following ActionScript on Frame 1 of the Timeline: import mx.transitions.Tween; import mx.transitions.easing.*; this.createEmptyMovieClip("box_mc", this.getNextHighestDepth()); with (box_mc) { beginFill(0xFF0000, 60); moveTo(0, 0);...
  • Page 496 Test the animation again (Control > Test Movie). Now, the box stops easing before it goes off the boundaries of the Stage. Combining the TransitionManager and Tween classes You can generate interesting effects when you combine the TransitionManager and Tween classes.
  • Page 497 You can find a sample source file that adds scripted animation using these classes. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 498: Using Filter Effects

    Using filter effects Filters are visual effects that you can apply to objects rendered at runtime by Flash Player, such as movie clip instances. The filters include drop shadow, blur, glow, bevel, gradient glow, and gradient bevel. You can also use an adjust color filter that lets you edit a movie clip’s brightness, contrast, saturation, and hue.
  • Page 499 For an example of using ActionScript to apply filters, you can find a sample source file, Filters.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters.
  • Page 500 statement lets you access classes without specifying their fully qualified names. import For example, to use a BlurFilter in a script, you must refer to it by its fully qualified name (flash.filters.BlurFilter) or import it; if you import it, you can refer to it by its class name (BlurFilter) in your code instead.
  • Page 501 For an example of using ActionScript to apply filters, you can find a sample source file, Filters.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters.
  • Page 502 To modify a filter’s properties when applied to a movie clip instance: Create a new Flash document and save the file as modifyFilter.fla. Add the following ActionScript to Frame 1 of the Timeline: this.createEmptyMovieClip("my_mc", 10); // draw square with (my_mc) { beginFill(0xFF0000, 100);...
  • Page 503 For an example of using ActionScript to apply filters, you can find a sample source file, Filters.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters.
  • Page 504 About error handling, performance, and filters One problem that arises if you use too many filters in an application is the potential to use large amounts of memory and cause Flash Player performance to suffer. Because a movie clip with filters attached has two bitmaps that are both 32-bit, these bitmaps can cause your application to use a significant amount of memory if you use many bitmaps.
  • Page 505: Working With Filters Using Actionscript

    Working with filters using ActionScript The flash.filters package contains classes for the bitmap filter effects that are new in Flash Player 8. Filters let you use ActionScript to apply rich visual effects, such as blur, bevel, glow, and drop shadow, to text, movie clip, and button instances. You can also use the Flash authoring tool to apply filter effects to objects such as text, images, and video.
  • Page 506 For an example of using ActionScript to apply filters, you can find a sample source file, Filters.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters.
  • Page 507 Using the blur filter The BlurFilter class lets you apply a blur visual effect to a variety of objects in Flash. A blur effect softens the details of an image. You can produce blurs that range from creating a softly unfocused look to a Gaussian blur, a hazy appearance like viewing an image through semi- opaque glass.
  • Page 508 To blur an image based on the mouse pointer’s position: Create a new Flash document and save it as dynamicblur.fla. Add the following code to Frame 1 of the Timeline: import flash.filters.BlurFilter; System.security.allowDomain("http://www.helpexamples.com"); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip) { // Center the target_mc movie clip on the Stage.
  • Page 509 Select Control > Test Movie to test the Flash document. Move the mouse pointer along the x-axis to modify the amount of horizontal blurring. The instance blurs more when the pointer moves farther away from the horizontal center of the Stage. Moving the pointer along the y-axis causes the vertical blurring to increase or decrease, depending on the distance from the vertical center of the Stage.
  • Page 510 To use the drop shadow filter: Create a new Flash document and save it as dropshadow.fla. Add the following ActionScript to Frame 1 of the Timeline: // import the filter classes import flash.filters.DropShadowFilter; // create a movie clip called shapeClip this.createEmptyMovieClip("shapeClip", 1);...
  • Page 511 Select Control > Test Movie to test the Flash document. Move the mouse pointer along the x-axis to change the value of the drop shadow’s distance, and move the mouse pointer along the y-axis to change the amount of blur applied to the movie clip instance.
  • Page 512 To create a drop shadow that follows the mouse pointer: Create a new Flash document and save it as dropshadowmouse.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.DropShadowFilter; System.security.allowDomain("http://www.helpexamples.com"); var dropShadow:DropShadowFilter = new DropShadowFilter(4, 45, 0x000000, 0.8, 10, 10, 2, 2);...
  • Page 513 You can also apply drop shadows to dynamically loaded semitransparent PNG images. In the following procedure, the drop shadow filter is applied only to the solid area of the PNG, not the transparency. To apply a drop shadow to a semitransparent image: Create a new Flash document and save it as dropshadowTransparent.fla.
  • Page 514 The following procedure demonstrates how you can apply a glow filter to a dynamically created movie clip on the Stage. Moving your mouse pointer around the Stage causes the movie clip’s blur to change, and clicking the dynamically created shape causes the filter’s strength to increase.
  • Page 515 Select Control > Test Movie to test the document. The amount of horizontal and vertical blurring is calculated by the mouse pointer’s current position. As you move the mouse pointer to the upper-left _xmouse _ymouse corner of the Stage, the amount of horizontal and vertical blurring decreases. Conversely, as the mouse pointer moves to the lower-right corner of the Stage, the amount of horizontal and vertical blurring increases.
  • Page 516 To apply a gradient glow filter: Create a new Flash document and save it as gradientglow.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.GradientGlowFilter; // create a new shapeClip instance var shapeClip:MovieClip = this.createEmptyMovieClip("shapeClip", 10); // use Drawing API to create a shape with (shapeClip) { beginFill(0xFF0000, 100);...
  • Page 517 Select Control > Test Movie to test the document. As you move your mouse pointer around the Stage, the gradient glow filter’s blur increases and decreases strength. Click the left mouse button to increase the glow’s strength. Using the bevel filter The BevelFilter class lets you add a bevel effect to a variety of objects in Flash.
  • Page 518 To use the bevel filter: Create a new Flash document and save it as bevel.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.BevelFilter; // define a bevel filter var bevel:BevelFilter = new BevelFilter(4, 45, 0xFFFFFF, 1, 0xCC0000, 1, 10, 10, 2, 3);...
  • Page 519 Select Control > Test Movie to test the Flash document. When you move the mouse pointer along the x-axis, the offset distance of the bevel increases or decreases. When you move the mouse pointer along the y-axis, the mouse pointer’s current coordinates modifies the amount of horizontal and vertical blurring. About the gradient bevel filter The gradient bevel filter is applied to an object as a rectangle, with the colors of the gradient distributed to three portions of the rectangle: two bevel edges (a highlight and a shadow) and...
  • Page 520 The different properties of the gradient bevel filter control the way the filter is applied. The colors of the gradient bevel are set in the colors array. The actual distribution of colors in each portion of the rectangle is determined by the ratios array. The distance property determines the offset distance, or how many pixels away from the object the bevel edge is applied.
  • Page 521 The last four colors range from 129 through 255, increasing in value so each value is greater than or equal to the previous one. This is the second bevel edge, for example, your shadow. If you think of a gradient as composed of stripes of various colors, blending into each other, each ratio value sets the number of pixels for the associated color, thus setting the width of the color stripe in the gradient.
  • Page 522 The following figure shows the gradient bevel filter created by the code above, a nine-color rainbow bevel applied to a red rectangle movie clip: The dashed line shows how angles are determined. The figure shows how the angle of 225° is realized on the filter, and also shows each ratio value for each color.
  • Page 523 square_mc.lineTo(40, 200); square_mc.lineTo(40, 40); square_mc.endFill(); /* GradientBevelFilter(distance:Number, angle:Number, colors:Array, alphas:Array, ratios:Array, blurX:Number, blurY:Number, strength:Number, quality:Number, type:String, knockout:Boolean) */ // create colors, alphas, and ratios arrays var colors:Array = [0x0000FF, 0x00FF00, 0x9900FF, 0xFFFF00, 0xFF0000, 0xFFFF00, 0x9900FF, 0x00FF00,0x000000];//blue, green, purple, yellow, red, yellow, purple, green, black var alphas:Array = [1, 1, 1, 1, 1, 1, 1, 1, 1];...
  • Page 524 To use the gradient bevel filter: Create a new Flash document and save it as gradientbevel.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.GradientBevelFilter; var shapeClip:MovieClip = this.createEmptyMovieClip("shape_mc", 1); with (shapeClip) { beginFill(0xFF0000, 100); moveTo(0, 0); lineTo(200, 0);...
  • Page 525 Using the color matrix filter The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the ARGB color and alpha values of every pixel on the input image to produce a result with a new set of ARGB color and alpha values.
  • Page 526 You could also create an animated brightness effect by combining the Tween class with the ColorMatrixFilter class, as the next procedure shows. To animate the brightness level of an instance by using the Tween class: Create a new Flash document and save it as brightnesstween.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.ColorMatrixFilter;...
  • Page 527 The first section of code uses the MovieClipLoader class to load a JPEG image onto the Stage. After the image completely loads, you reposition the image to the center of the Stage. Then you use the Tween class to animate the image brightness level. To animate the brightness, you use the method, which registers an event handler that Object.watch()
  • Page 528 To use the convolution filter to modify an image’s color: Create a new Flash document and save it as convolution.fla. Add the following ActionScript to Frame 1 of the Timeline: import flash.filters.ConvolutionFilter; import flash.display.BitmapData; this.createEmptyMovieClip("shape_mc", 1); shape_mc.createEmptyMovieClip("holder_mc", 1); var imageLoader:MovieClipLoader = new MovieClipLoader(); imageLoader.loadClip("http://www.helpexamples.com/flash/images/ image1.jpg", shape_mc.holder_mc);...
  • Page 529 This filter is only available by using ActionScript. For more information on this filter, see DisplacementMapFilter (flash.filters.DisplacementMapFilter) in the ActionScript 2.0 Language Reference. The following procedure loads a JPEG image and applies a displacement map filter to it, which causes the image to look distorted. Whenever the user moves the mouse, the displacement map is regenerated.
  • Page 530: Manipulating Filter Effects With Code

    Select Control > Test Movie to test the document. Move your mouse pointer around the Stage to re-create a displacement map by calling the method, which changes the appearance of the JPEG image. perlinNoise() Manipulating filter effects with code Flash Basic 8 and Flash Professional 8 let you dynamically add various filters to your movie clips, text fields, and buttons on the Stage, instead of having to add filters in the Flash Professional 8 authoring environment (using the Filters tab in the Property inspector).
  • Page 531 Setting the property duplicates the filters array passed in and does not store it as a filters reference. When getting the filters property, it returns a new copy of the array. One negative implication of this approach is that the following code does not work: // does not work my_mc.filters[0].blurX = 20;...
  • Page 532 Moving the mouse pointer along the -axis modifies the blur filter’s property. blurX Moving the mouse pointer along the -axis modifies the blur filter’s property. The blurY closer the mouse pointer is to the upper-left corner of the Stage, the less blurring is applied to the movie clip.
  • Page 533 The preceding code is separated into three sections. The first section imports the required classes and packages. The second section creates a nested movie clip that is used to load an image and apply filters to the holder movie clip. The final section of code creates a new MovieClipLoader instance and a listener for the movie clip loader.
  • Page 534: Creating Bitmaps With The Bitmapdata Class

    You can find a sample source file that uses the BitmapData class to manipulate an image. Find the file called BitmapData.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\BitmapData. Animation, Filters, and Drawings...
  • Page 535 On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/BitmapData. The following procedure dynamically loads a JPEG image onto the Stage, and uses the BitmapData class to create a noise effect, similar to static on a television. The noise effect is redrawn with a random pattern every 100 milliseconds (1/10 of a second).
  • Page 536 Select Control > Test Movie to test the document. Moving the mouse pointer along the x-axis affects the parameter; moving the mouse pointer along the y-axis affects the parameter. high The BitmapData class also lets you distort a dynamically loaded image by using a combination of a method effect and a displacement map filter.
  • Page 537: About Blending Modes

    This code example consists of five logical sections. The first section imports the necessary classes for the example. The second block of code creates a nested movie clip and loads a JPEG image from a remote server. The third block of code creates a new BitmapData instance named , which is the same size as the dimensions of the Stage.
  • Page 538 normal Used to specify that the pixel values of the blend image override those of the base image. overlay Commonly used to create shading effects. screen Commonly used to create highlights and lens flares. subtract Commonly used to create an animated darkening dissolve effect between two images.
  • Page 539 var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip) { var blendModeClip:MovieClip = target_mc.createEmptyMovieClip("blendModeType_mc", 20); with (blendModeClip) { beginFill(0x999999); moveTo(0, 0); lineTo(target_mc._width / 2, 0); lineTo(target_mc._width / 2, target_mc._height); lineTo(0, target_mc._height); lineTo(0, 0); endFill(); target_mc._x = (Stage.width - target_mc._width) / 2; target_mc._y = (Stage.height - target_mc._height) / 2;...
  • Page 540: About Operation Order

    About operation order The following list is the order of operations in which a filters array, blend modes, color transforms, and mask layers are attached or performed for a movie clip instance: The movie clip’s bitmap is updated from vector content (the property is cacheAsBitmap set to...
  • Page 541 You can find a sample source file, drawingapi.fla, in the Samples folder on your hard disk, which shows you how to use the Drawing API in a Flash application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DrawingAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DrawingAPI.
  • Page 542 To draw a curve: Create a new Flash document and save it as curve.fla. Add the following ActionScript to Frame 1 of the Timeline: this.createEmptyMovieClip("circle_mc", 1); with (circle_mc) { lineStyle(4, 0x000000, 100); beginFill(0xFF0000); moveTo(200, 300); curveTo(300, 300, 300, 200); curveTo(300, 100, 200, 100); curveTo(100, 100, 100, 200);...
  • Page 543 You can find a sample source file, drawingapi.fla, in the Samples folder on your hard disk, which shows you how to use the Drawing API in a Flash application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DrawingAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DrawingAPI.
  • Page 544 To create a rounded rectangle: Create a new Flash document and save it as roundrect.fla. Add the following ActionScript code to Frame 1 of the Timeline: this.createEmptyMovieClip("rectangle_mc", 10); rectangle_mc._x = 100; rectangle_mc._y = 100; drawRoundedRectangle(rectangle_mc, 240, 180, 20, 0x99FF00, 100); function drawRoundedRectangle(target_mc:MovieClip, boxWidth:Number, boxHeight:Number, cornerRadius:Number, fillColor:Number, fillAlpha:Number):Void {...
  • Page 545 To create a circle: Create a new Flash document and save as circle2.fla. Add the following ActionScript code to Frame 1 of the Timeline: this.createEmptyMovieClip("circle_mc", 10); circle_mc._x = 100; circle_mc._y = 100; drawCircle(circle_mc, 100, 0x99FF00, 100); function drawCircle(target_mc:MovieClip, radius:Number, fillColor:Number, fillAlpha:Number):Void { var x:Number = radius;...
  • Page 546 You can find a sample source file, drawingapi.fla, in the Samples folder on your hard disk, which shows you how to use the Drawing API in a Flash application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DrawingAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DrawingAPI.
  • Page 547 Using complex gradient fills The Flash Drawing API supports gradient fills as well as solid fills. The following procedure creates a new movie clip on the Stage, use the Drawing API to create a square, and then fills the square with a radial red and blue gradient. To create a complex gradient: Create a new Flash document and save it as radialgradient.fla.
  • Page 548 Using line styles The Flash Drawing API lets you specify a line style that Flash uses for subsequent calls to until you call MovieClip.lineTo() MovieClip.curveTo() MovieClip.lineStyle() with different parameters, as follows: lineStyle(thickness:Number, rgb:Number, alpha:Number, pixelHinting:Boolean, noScale:String, capsStyle:String, jointStyle:String, miterLimit:Number) You can call in the middle of drawing a path to specify different MovieClip.lineStyle() styles for different line segments within a path.
  • Page 549 with (line2_mc) { createTextField("label_txt", 1, 5, 10, 100, 20); label_txt.text = "square"; lineStyle(20, 0x99FF00, 100, true, "none", "square", "miter", 0.8); moveTo(0, 0); lineTo(200, 0); _x = 50; _y = 150; // line 3 (capsStyle: none) this.createEmptyMovieClip("line3_mc", 30); with (line3_mc) { createTextField("label_txt", 1, 5, 10, 100, 20);...
  • Page 550 To create a hairline stroke: Create a new Flash document and save it as hairline.fla. Add the following ActionScript to Frame 1 of your Timeline: this.createEmptyMovieClip("drawing_mc", 10); // create a red, hairline thickness line drawing_mc.lineStyle(0, 0xFF0000, 100); drawing_mc.moveTo(0, 0); drawing_mc.lineTo(200, 0); drawing_mc.lineTo(200, 100);...
  • Page 551 Setting line alpha The third parameter in the method, , lets you control the transparency lineStyle() alpha (alpha) level for the line. Transparency is a numerical value between 0 and 100, where 0 represents a completely transparent line, and 100 is completely opaque (visible). Setting line pixel hinting (pixelHinting) The pixel hinting for strokes parameter, , means that line and curve anchors are...
  • Page 552 To set different caps styles: Create a new Flash document and save it as capsstyle2.fla. Add the following ActionScript to Frame 1 of the Timeline: var lineLength:Number = 100; // round this.createEmptyMovieClip("round_mc", 10); round_mc.lineStyle(20, 0xFF0000, 100, true, "none", "round"); round_mc.moveTo(0, 0); round_mc.lineTo(lineLength, 0);...
  • Page 553 You can set the following three types of joint styles for the parameter: jointStyle (default) round miter bevel The following example demonstrates the differences between each of the three joint styles. To set different joint styles: Create a new Flash document and save it as jointstyles.fla. Add the following ActionScript to Frame 1 of the Timeline: var lineLength:Number = 100;...
  • Page 554 var lbl:TextField = bevel_mc.createTextField("label_txt", 10, 0, lineLength + 20, lineLength, 20); lbl.autoSize = "center"; lbl.text = "bevel"; Flash uses the Drawing API to draw three triangles on the Stage. Each triangle has a different value for its joint style. Save the Flash document and select Control > Test Movie to test the document. Setting line miter (miterLimit) property is a numerical value that indicates the limit at which a miter joint miterLimit...
  • Page 555 You can find a sample source file, drawingapi.fla, in the Samples folder on your hard disk, which shows you how to use the Drawing API in a Flash application. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DrawingAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DrawingAPI.
  • Page 556: Understanding Scaling And Slice Guides

    Understanding scaling and slice guides You can use 9-slice scaling (Scale-9) to specify component-style scaling for movie clips. 9-slice scaling lets you create movie clip symbols that scale appropriately for use as user interface components, as opposed to the type of scaling typically applied to graphics and design elements.
  • Page 557 You can see that even though the component resized, the Button’s border and text label do not distort. The button’s label remained centered and maintained its font size. Although components of version 2 of the Macromedia Component Architecture do not use 9-slice scaling, components handle scaling in the version 2 component architecture so the outlines do not change size (as shown in the next figure).
  • Page 558 Working with 9-slice scaling in ActionScript In the following example, you use the drawing tools to draw a 300 pixel by 300 pixel square which is resized by using 9-slice scaling. The square is split up into nine smaller squares, each one approximately 100 pixels wide by 100 pixels high.
  • Page 559 Add the following ActionScript to Frame 1 of the main Timeline: import mx.controls.Button; import flash.geom.Rectangle; var grid:Rectangle = new Rectangle(100, 100, 100, 100); var small_button:Button = this.createClassObject(Button, "small_button", 10, {label:"Small"}); small_button.move(10, 10); small_button.addEventListener("click", smallHandler); function smallHandler(eventObj:Object):Void { my_mc._width = 100; my_mc._height = 100;...
  • Page 560 Next, you create a new Button component instance and give it an instance name of . Whenever you click this button, the movie clip that you created earlier small_button resizes to 100 pixels wide by 100 pixels high. The fourth section of code dynamically creates a new Button instance named which, when clicked, resizes the large_button...
  • Page 561: Chapter 14: Creating Interaction With Actionscript

    Creating Interaction with ActionScript In simple animations, Macromedia Flash Player plays the scenes and frames of a SWF file sequentially. In an interactive SWF file, your audience uses the keyboard and mouse to jump to different parts of a SWF file, move objects, enter information in forms, and perform many other interactive operations.
  • Page 562: About Events And Interaction

    About events and interaction Whenever a user clicks the mouse or presses a key, that action generates an event. These types of events are generally called user events because they are generated in response to some action by the user. You can write ActionScript to respond to, or handle, these events. For example, when a user clicks a button, you might want to send the playhead to another frame in the SWF file or load a new web page into the browser.
  • Page 563 The following example uses the global function within a button object’s gotoAndPlay() event handler to send the playhead of the timeline that contains the button to onRelease Frame 10: jump_btn.onRelease = function () { gotoAndPlay(10); In the next example, the method sends the timeline of a movie MovieClip.gotoAndStop() clip instance named...
  • Page 564 HTML anchor tag ( <a></a> For example, the following code opens the macromedia.com home page in a blank browser window when the user clicks the button instance named homepage_btn // Attach to frame homepage_btn.onRelease = function () {...
  • Page 565 You can also send variables along with the URL, using methods. This is useful if POST the page you are loading from an application server, such as a ColdFusion server (CFM) page, expects to receive form variables. For example, suppose you want to load a CFM page named addUser.cfm that expects two form variables, first .
  • Page 566: Creating Interactivity And Visual Effects

    Creating interactivity and visual effects To create interactivity and other visual effects, you need to understand the following techniques: “Creating a custom mouse pointer” on page 566 “Getting the pointer position” on page 567 “Capturing keypresses” on page 569 “Setting color values” on page 572 “Creating sound controls”...
  • Page 567 Select Frame 1 of the Timeline, and type the following code in the Actions panel: Mouse.hide(); cursor_mc.onMouseMove = function() { this._x = _xmouse; this._y = _ymouse; updateAfterEvent(); method hides the pointer when the movie clip first appears on the Mouse.hide() Stage;...
  • Page 568 Each timeline has an property that returns the location of the pointer _xmouse _ymouse within its coordinate system. The position is always relative to the registration point. For the main timeline ( ), the registration point is the upper left corner. For a movie clip, the _level0 registration point depends on the registration point set when the clip was created or its placement on the Stage.
  • Page 569 Capturing keypresses You can use the global handler to intercept the built-in behavior of keypresses in Flash on() Player, as shown in the following example: /* When you press the Left or Right Arrow key, the movie clip to which the handler is attached changes transparency.
  • Page 570 To decide which keys to use and determine their virtual key codes, use one of the following approaches: See the list of key codes in Appendix C, “Keyboard Keys and Key Code Values.” Use a Key class constant. (In the Actions toolbox, click ActionScript 2.0 Classes > Movie > Key >...
  • Page 571 To check if the Left Arrow key is pressed and to move the car movie clip accordingly, add code to the body of the event handler. onEnterFrame Your code should look like the following example (new code is in boldface): var distance:Number = 10;...
  • Page 572 Setting color values You can use the methods of the built-in ColorTransform class (flash.geom.ColorTransform) to adjust the color of a movie clip. The property of the ColorTransform class assigns hexadecimal red, green, blue (RGB) values to the movie clip. The following example uses to change an object’s color, based on which button the user clicks.
  • Page 573 Repeat step 7 for the other buttons ( , and ) to change the red_btn green_btn black_btn color of the movie clip to the corresponding color. Your code should now look like the following example (new code is in bold): import flash.geom.ColorTransform;...
  • Page 574 Select Export for ActionScript and Export in First Frame; then give the sound the identifier a_thousand_ways Add a button to the Stage and name it play_btn Add a button to the Stage and name it stop_btn Select Frame 1 in the main Timeline, and select Window > Actions. Add the following code to the Actions panel: var song_sound:Sound = new Sound();...
  • Page 575 Select Frame 1 of the main Timeline, and select Window > Actions. Enter the following code into the Actions panel: this.createTextField("volume_txt", 10, 30, 30, 200, 20); volume_mc.top = volume_mc._y; volume_mc.bottom = volume_mc._y; volume_mc.left = volume_mc._x; volume_mc.right = volume_mc._x + 100; volume_mc._x += 100;...
  • Page 576 Enter the following code into the Actions panel: balance_mc.top = balance_mc._y; balance_mc.bottom = balance_mc._y; balance_mc.left = balance_mc._x; balance_mc.right = balance_mc._x + 100; balance_mc._x += 50; balance_mc.handle_btn.onPress = function() { startDrag(this._parent, false, this._parent.left, this._parent.top, this._parent.right, this._parent.bottom); balance_mc.handle_btn.onRelease = function() { stopDrag(); var level:Number = Math.ceil((this._parent._x - this._parent.left - 50) * 2);...
  • Page 577 To detect a collision between a movie clip and the mouse pointer: Select the first frame on Layer 1 in the Timeline. Select Window > Actions to open the Actions panel, if it is not already open. Add the following code in the Actions panel: this.createEmptyMovieClip("box_mc", 10);...
  • Page 578 Select Control > Test Movie, and drag the movie clip to test the collision detection. Whenever the bounding box of the car intersects the bounding box of the area, the status is true For more information, see hitTest (MovieClip.hitTest method) in the ActionScript 2.0 Language Reference.
  • Page 579: Creating Runtime Data Bindings Using Actionscript

    Using Flash. You can also find additional information in the following online articles: Building a Tip of the day Application (Part Data Binding in Macromedia Flash MX Professional 2004, Building a Google Search Application with Macromedia Flash MX Professional.
  • Page 580 You can use ActionScript instead of the Bindings tab to create bindings between components. Adding code is often faster and more efficient than relying on the authoring environment. Using ActionScript to create bindings is necessary when you use code to add components to an application.
  • Page 581 Insert a new layer and name it actions. Add the following ActionScript to Frame 1 of the actions layer: var src:mx.data.binding.EndPoint = new mx.data.binding.EndPoint(); src.component = in_ti; src.property = "text"; src.event = "focusOut"; var dest:mx.data.binding.EndPoint = new mx.data.binding.EndPoint(); dest.component = out_ti; dest.property = "text";...
  • Page 582 If you want to modify the text in the text input field from the previous exercise, your out_ti code can become a lot more complex. If you use the Component inspector to set up bindings, by default you create a two-way connection. This means that if you change either text field on the Stage, the other text field changes as well.
  • Page 583 You can use the Binding classes with most user interface components of version 2 of the Macromedia Component Architecture, not just the TextInput component. The following example demonstrates how to use ActionScript to bind CheckBox instances and Label components during runtime.
  • Page 584 Using components, bindings, and custom formatters Custom formatters help you format complex data in a specific way. You can also use custom formatting to help display images, HTML formatted text, or other components within a component such as the DataGrid. The following example illustrates how useful custom formatters can be.
  • Page 585 Select Control > Test Movie to test the document again. Now the text field displays the entire date, although it is awkward and lacks formatting. Depending on your own time zone and selected date, the date might appear similar to this: Thu Nov 4 00:00:00 GMT-0800 2004 Even though the binding works properly and displays the...
  • Page 586 The first section of code defines the new class called DateFormat, which extends the CustomFormatter class in the package. Remember that Flash compiles mx.data.binding the binding classes in the DataBindingClasses component file, so you can’t view them directly or find them within the Classes folder in the Flash install directory. The only method you use is the method, which converts the date instance into format()
  • Page 587 Adding and binding components on the Stage One of the biggest advantages to using the binding classes with ActionScript is that you can create bindings between components that Flash has added to the Stage at runtime. Imagine creating your own custom class that adds the appropriate text fields to the Stage at runtime, and then validates the necessary data and adds the necessary bindings.
  • Page 588: Deconstructing A Sample Script

    Deconstructing a sample script In the sample SWF file zapper.swf (which you can view in Using Flash Help), when a user drags the bug to the electrical outlet, the bug falls and the outlet shakes. The main timeline has only one frame and contains three objects: the ladybug, the outlet, and a reset button. Each object is a movie clip instance.
  • Page 589 The bug’s instance name is , and the outlet’s instance name is . In the bug_mc zapper_mc script, the bug is referred to as because the script is attached to the bug and the reserved this word refers to the object that contains it. this There are event handlers with several different events: , and...
  • Page 590 Creating Interaction with ActionScript...
  • Page 591: Chapter 15: Working With Images, Sound, And Video

    Working with Images, Sound, and Video If you import an image or a sound while you author a document in Macromedia Flash Basic 8 or Macromedia Flash Professional 8, the image and sound are packaged and stored in a SWF file when you publish it.
  • Page 592: About Loading And Working With External Media

    You can load several types of media files into a Flash application at runtime: SWF, MP3, JPEG, GIF, PNG, and FLV files. However, not all versions of Flash Player support each kind of media. For more information on the image file types that are supported in Macromedia Flash Player 8, see “Loading external SWF and image files”...
  • Page 593: Loading External Swf And Image Files

    In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. Loading external SWF and image files To load a SWF or image file, use the global function, the loadMovie()
  • Page 594 For more information about loading external SWF and image files, see “About loading SWF files and the root timeline” on page 597. To preload SWF and JPEG files into movie clip instances, you can use the MovieClipLoader class. This class provides an event listener mechanism to give notification about the status of file downloads into movie clips.
  • Page 595 Register the listener object with the MovieClipLoader object In order for the listener object to receive the loading events, you must register it with the MovieClipLoader object, as shown in the following code: my_mcl.addListener(mclListener); Begin loading the file (image or SWF) into a target clip To start downloading an image or SWF file, you use the method, as shown in the following...
  • Page 596 Add the following code to the Actions panel: var my_pb:mx.controls.ProgressBar; my_pb.mode = "manual"; this.createEmptyMovieClip("img_mc", 999); var my_mcl:MovieClipLoader = new MovieClipLoader(); var mclListener:Object = new Object(); mclListener.onLoadStart = function(target_mc:MovieClip):Void { my_pb.label = "loading: " + target_mc._name; mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number):Void { var pctLoaded:Number = Math.ceil(100 * (numBytesLoaded / numBytesTotal));...
  • Page 597 SWF file. You can find the sample source files, gallery_tree.fla and gallery_tween.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.
  • Page 598: About Loading And Using External Mp3 Files

    This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\Components\Jukebox. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/Components/Jukebox.
  • Page 599 This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\Components\Jukebox. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/Components/Jukebox.
  • Page 600 The following example uses to check the bytes loaded for a Sound object at setInterval() predetermined intervals. To preload an MP3 file: Create a new FLA file called preloadMP3.fla. Select Frame 1 on the Timeline and type the following code in the Actions panel: // Create a new Sound object to play the sound.
  • Page 601 This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\Components\Jukebox. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/Components/Jukebox.
  • Page 602: Assigning Linkage To Assets In The Library

    This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\Components\Jukebox. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/Components/Jukebox.
  • Page 603: About Using Flv Video

    Select Frame 1 on the Timeline, and type the following code in the Actions panel: import flash.display.BitmapData; // Create imageBmp and attach the bitmap from the library. var imageBmp:BitmapData = BitmapData.loadBitmap("myImage"); // create movie clip and attach imageBmp this.createEmptyMovieClip("imageClip", 10); imageClip.attachBitmap(imageBmp, 2);...
  • Page 604 FLVPlayback component to play FLV files or use the VideoPlayback class to create a custom video player that loads FLV files dynamically (see www.macromedia.com/devnet/flash www.macromedia.com/support/documentation/). For information on using FLV video with the FLVPlayback and Media components, see the following sections: “FLVPlayback Component (Flash Professional Only)” on page 489 “Media components (Flash Professional only)”...
  • Page 605 Captioning video content is easier with external FLV files because you can use event handlers to access metadata for the video. To load FLV files from a web server, you might need to register the file extension and MIME type with your web server; check your web server documentation. The MIME type for FLV files is video/x-flv.
  • Page 606 Playing back external FLV files dynamically You can load FLV files at runtime to play in a SWF file. You can load them into a video object or into a component such as the FLVPlayback component. The following example shows how to play back a file named clouds.flv in a video object. To play back an external FLV file in a Flash document: Create a new Flash document called playFLV.fla.
  • Page 607 For information on preloading FLV files, see “Preloading FLV files” on page 507. For information on dynamically loading FLV video into components, see “Creating an application with the FLVPlayback component” on page 491. For information on FLV files and the server, and FLV files and playing FLV files locally on the Macintosh, see “About configuring FLV files for hosting on a server”...
  • Page 608 Select Frame 1 on the Timeline, and then type the following code in the Actions panel: inv_btn.onRelease = function(){ getURL("http://www.macromedia.com"); Make other modifications to the banner, such as adding graphics or text. Select Control > Test Movie to test the banner in Flash Player.
  • Page 609 In this example, you created a banner and resized its dimensions to the established, standardized dimensions that the Interactive Advertising Bureau specifies. For information on standard advertising dimensions (and many other useful guidelines), see the Interactive Advertising Bureau’s Standards and Guidelines page at www.iab.net/standards/adunits.asp. Despite standardized guidelines, ensure that you confirm the advertising guidelines for the advertising service, client, or website that you’re advertising with first.
  • Page 610 Type the following code in the Actions panel: var connection_nc:NetConnection = new NetConnection(); connection_nc.connect(null); var stream_ns:NetStream = new NetStream(connection_nc); my_video.attachVideo(stream_ns); stream_ns.play("http://www.helpexamples.com/flash/video/ lights_short.flv"); this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22); var loaded_interval:Number = setInterval(checkBytesLoaded, 500, stream_ns); function checkBytesLoaded(my_ns:NetStream) { var pctLoaded:Number = Math.round(my_ns.bytesLoaded / my_ns.bytesTotal * 100);...
  • Page 611 Working with cue points You can use several different kinds of cue points with Flash Video. You can use ActionScript to interact with cue points that you embed in an FLV file (when you create the FLV file), or that you create by using ActionScript. Navigation cue points You embed navigation cue points in the FLV stream and FLV metadata packet when you encode the FLV file.
  • Page 612 The following code traces cue points in an FLV file: var connection_nc:NetConnection = new NetConnection(); connection_nc.connect(null); var stream_ns:NetStream = new NetStream(connection_nc); stream_ns.onMetaData = function(metaProp:Object) { trace("The metadata:"); traceMeta(metaProp); // traceObject(metaProp, 0); my_video.attachVideo(stream_ns); stream_ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); function traceMeta(metaProp:Object):Void { var p:String; for (p in metaProp) { switch (p) { case "cuePoints"...
  • Page 613 trace(indentString + " " + i + ": " + obj[i]); The following output appears: The metadata: canSeekToEnd: true cuePoints: cuePoints[0]: name: point1 time: 0.418 type: navigation parameters: lights: beginning cuePoints[1]: name: point2 time: 7.748 type: navigation parameters: lights: middle cuePoints[2]: name: point3 time: 16.02...
  • Page 614 Using embedded cue points with the FLVPlayback component (Flash Professional only) You can view cue points for an FLV file in the Property inspector when you use the FLVPlayback component. After you set the property for the FLVPlayback contentPath instance, you can view any cue points that are embedded in the video file. Using the Parameters tab, find the property, and click the magnifying glass icon to see a list cuePoints...
  • Page 615 Select Control > Test Movie to test the SWF file. The elapsed time appears in the TextArea instance when the playhead passes each cue point embedded in the document. For more information on working with the FLVPlayback component, see “FLVPlayback Component (Flash Professional Only)”...
  • Page 616 Select Frame 1 on the Timeline, and type the following code in the Actions panel: var my_flvPb:mx.video.FLVPlayback; my_flvPb.contentPath = "http://www.helpexamples.com/flash/video/ clouds.flv"; // Create cuePoint object. var cuePt:Object = new Object(); cuePt.time = 1; cuePt.name = "elapsed_time"; cuePt.type = "actionscript"; // Add AS cue point. my_flvPb.addASCuePoint(cuePt);...
  • Page 617 Select the Parameters tab, and click Launch Component Inspector. In the Component inspector, type http://www.helpexamples.com/flash/video/clouds.flv in the URL text box. Open the Actions panel (Window > Actions), and type the following code in the Script pane: import mx.controls.MediaPlayback; var my_mp:MediaPlayback; my_mp.autoPlay = false;...
  • Page 618 Alternatively, you can also seek to a specified duration of the FLV file, using the method. seek() In the following examples, you add a button that you use to jump between cue points or a specified duration in a FLV file that plays in the FLVPlayback component, and a button to jump to a specified cue point.
  • Page 619 Select the component and open the Property inspector (Window > Properties > Properties). Type my_flvPb in the Instance Name text box. Drag an instance of the Button component from the Components panel to the Stage. Select the Button component and type my_button in the Instance Name text box. Select Frame 1 on the Timeline and type the following code in the Actions panel: import mx.video.FLVPlayback;...
  • Page 620 When you type the URL in the contentPath text box, the cue points appear in the Parameters tab (next to cuePoint parameter). Therefore, you can determine the name of the cue point that you want to find in your code. If you click the magnifying glass icon, you can view all of the video file’s cue points and information about each cue point in a table.
  • Page 621 To work with , you must have Flash Video that contains metadata. If NetStream.onMetaData you encode FLV files using Flash 8 Video Encoder, your FLV file will have metadata information in it (see the following example for a list of metadata in a FLV file encoded with Flash 8 Video Encoder).
  • Page 622 Type the following code in the Actions panel: // Create a NetConnection object. var netConn:NetConnection = new NetConnection(); // Create a local streaming connection. netConn.connect(null); // Create a NetStream object and define an onStatus() function. var nStream:NetStream = new NetStream(netConn); // Attach the NetStream video feed to the Video object.
  • Page 623 This issue affects all FLV files placed on Windows 2003 server, including files you make with earlier versions of the Flash authoring tool, the Macromedia Flash Video Kit for Dreamweaver MX 2004. These files work correctly if you test them on other operating systems.
  • Page 624: About Creating Progress Animations For Media Files

    (Macintosh) myDrive:myFolder:myFLV.flv You can also create a projector file for a CD-ROM you intend to use for Macintosh playback. For the latest information on Macintosh CD-ROMs and FLV files, see www.macromedia.com/go/3121b301. About creating progress animations for media files ActionScript provides several ways to preload or track the downloading progress of external media.
  • Page 625 You can find a sample source file that uses scripted animation to create a progress bar animation. Find tweenProgress.fla in the Samples folder on your hard disk: In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 626 Select Frame 1 of the Timeline, and then type the following code in the Actions panel: //create clips to hold your content this.createEmptyMovieClip("progressBar_mc", 0); progressBar_mc.createEmptyMovieClip("bar_mc", 1); progressBar_mc.createEmptyMovieClip("stroke_mc", 2); //use drawing methods to create a progress bar with (progressBar_mc.stroke_mc) { lineStyle(0, 0x000000); moveTo(0, 0);...
  • Page 627 You can find a sample source file that uses scripted animation to create a progress bar animation. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 628 To create a progress bar for loading MP3 files: Create a new Flash document called loadSound.fla. Select Frame 1 on the Timeline and type the following code in the Actions panel. var pb_height:Number = 10; var pb_width:Number = 100; var pb:MovieClip = this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());...
  • Page 629 You can find a sample source file that uses scripted animation to create a progress bar animation. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 630 Creating a progress bar for loading FLV files with ActionScript You can create a progress bar to display the loading progress of an FLV file. For information on loading FLV files into a SWF file, see “Preloading FLV files” on page 609.
  • Page 631 Select Frame 1 in the Timeline and type the following code in the Actions panel: var connection_nc:NetConnection = new NetConnection(); connection_nc.connect(null); var stream_ns:NetStream = new NetStream(connection_nc); my_video.attachVideo(stream_ns); stream_ns.play("http://www.helpexamples.com/flash/video/ typing_short.flv"); this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22); this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth()); progressBar_mc.createEmptyMovieClip("bar_mc", progressBar_mc.getNextHighestDepth()); with (progressBar_mc.bar_mc) { beginFill(0xFF0000);...
  • Page 632 You can find a sample source file that uses scripted animation to create a progress bar animation. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.
  • Page 633: Chapter 16: Working With External Data

    Macromedia ColdFusion or Macromedia JRun) or another type of server-side script, such as PHP or Perl. Macromedia Flash Player can send and load data over HTTP or HTTPS or load from a local text file. You can also create persistent TCP/IP socket connections for applications that require low latency—for example, chat applications or stock quote services.
  • Page 634: Sending And Loading Variables

    Sending and loading variables A SWF file is a window for capturing and displaying information, much like an HTML page. However, SWF files can stay loaded in the browser and continuously update with new information without having to reload the entire page. Using ActionScript functions and methods, you can send information to and receive information from server-side scripts and receive information from text files and XML files.
  • Page 635 In the file myData.txt, you would have text similar to the following example: lastSiteVisited=www.macromedia.com If you used the following code, you could not trace the data that is loading: loadVariables("myData.txt", 0); trace(lastSiteVisited); // undefined Each function or method has a specific technique you can use to check data it has loaded.
  • Page 636 Creating a progress bar to display data loading progress The following exercise dynamically creates a simple preloader using the Drawing application programming interface (API) and displays the loading progress for an XML document. If the remote XML file loads too quickly to see the preloading effect, try uploading a larger XML file to the internet and loading that file.
  • Page 637 } else { trace("Unable to load XML"); my_xml.load("http://www.helpexamples.com/flash/xml/ds.xml"); pBar_mc.onEnterFrame = function() { var pctLoaded:Number = Math.floor(my_xml.getBytesLoaded() / my_xml.getBytesTotal() * 100); if (!isNaN(pctLoaded)) { pBar_mc.bar_mc._xscale = pctLoaded; pBar_mc.label_txt.text = pctLoaded + "% loaded"; if (pctLoaded >= 100) { pBar_mc.onEnterFrame = undefined; The previous code is broken down into seven sections.
  • Page 638: Using Http To Connect To Server-Side Scripts

    Select Control > Test Movie to test the Flash document. As the external XML file loads, the nested movie clip resizes to display the bar_mc download progress of the XML. Once the XML file has completely loaded, the event handler gets deleted so it doesn’t continue to calculate the download onEnterFrame progress.
  • Page 639 WNewton&highScore3=42885&playerName3=TJones You might need to URL-encode certain characters, such as the plus (+) sign or ampersand (&) characters. For more information, see www.macromedia.com/go/ tn_14143. For more information, see the following topic: “Using the LoadVars class” on page 639. Also, see loadVariables function, getURL function, loadMovie function, and the LoadVars entry in the ActionScript 2.0 Language Reference.
  • Page 640 You must have ColdFusion installed on your web server for this example. To load data with the LoadVars object: Create a CFM file in Macromedia Dreamweaver or in your favorite text editor. Add the following text to the file: <cfif StructKeyExists(Form, "emailTo")>...
  • Page 641 Create four input text fields on the Stage, and give them the following instance names: emailFrom_txt, emailTo_txt, emailSubject_txt, and emailBody_txt. Create a dynamic text field on the Stage with the instance name debug_txt. Create a button symbol, drag an instance on to the Stage, and give it an instance name of submit_btn.
  • Page 642 Flash Player 8 introduced the event handler for the LoadVars class, XML class, onHTTPStatus and MovieClipLoader class to allow users to access the status code from an HTTP request. This allows developers to determine why a particular load operation may have failed instead of only being able to determine that a load operation already has failed.
  • Page 643 The previous code creates a new text field on the Stage and enables text field autosizing. Next, a LoadVars object is created and two event handlers: onHTTPStatus onLoad event handler is new to Flash Player 8 and is invoked when a onHTTPStatus operation has completed.
  • Page 644: About File Uploading And Downloading

    About file uploading and downloading The FileReference class lets you add the ability to upload and download files between a client and server. Your users can upload or download files between their computer and a server. Users are prompted to select a file to upload or a location for download in a dialog box (such as the Open dialog box on the Windows operating system).
  • Page 645 646. You can find the sample source file for this example, FileUpload.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FileUpload. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FileUpload.
  • Page 646 About FileReference API functionality and security Flash Player and the FileReference API (see “About file uploading and downloading” on page 644) support file uploading and downloading up to 100 MB. The FileReference API does not let the Flash application that initiates the file transfer do the following: Access the uploaded or downloaded file Access the path of the file on the user’s computer When a server requires authentication, the only potentially successful operation is to perform...
  • Page 647 Following the example that builds the Flash application is an example that details the server- side code. Remember that image files are restricted in size: you can only upload images that are 200K or smaller. To build a FLA application using the FileReference API: Create a new Flash document and save it as fileref.fla.
  • Page 648 import flash.net.FileReference; imagePane.setSize(400, 350); imagePane.move(75, 25); uploadBtn.move(75, 390); uploadBtn.label = "Upload Image"; imageLbl.move(75, 430); imageLbl.text = "Select Image"; statusLbl.move(210, 390); statusLbl.text = "Status"; imagesCb.move(75, 450); statusArea.setSize(250, 100); statusArea.move(210, 410); /* The listener object listens for FileReference events. */ var listener:Object = new Object(); /* When the user selects a file, the onSelect() method is called, and passed a reference to the FileReference object.
  • Page 649 imagePane.addEventListener("complete", imageDownloaded); imagesCb.addEventListener("change", downloadImage); uploadBtn.addEventListener("click", uploadImage); /* If the image does not download, the event object's total property will equal -1. In that case, display a message to the user. */ function imageDownloaded(event:Object):Void { if (event.total == -1) { imagePane.contentPath = "Message"; /* When the user selects an image from the ComboBox, or when the downloadImage() function is called directly from the listener.onComplete() method, the downloadImage() function sets the...
  • Page 650 SWF file. You can find the sample source file for this example, FileUpload.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FileUpload. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FileUpload.
  • Page 651 array_push($files, array('./images/'.$file, filectime('./images/ '.$file))); usort($files, sorter); if (count($files) > $MAXIMUM_FILE_COUNT) { $files_to_delete = array_splice($files, 0, count($files) - $MAXIMUM_FILE_COUNT); for ($i = 0; $i < count($files_to_delete); $i++) { unlink($files_to_delete[$i][0]); print_r($files); closedir($directory); function sorter($a, $b) { if ($a[1] == $b[1]) { return 0; } else { return ($a[1] <...
  • Page 652: About Xml

    Message movie clip in the Library. You can find the sample source file for this example, FileUpload.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FileUpload. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FileUpload.
  • Page 653 One sample demonstrates how to create a web log tracker by loading, parsing, and manipulating XML data. You can find the sample source file, xml_blogTracker.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_BlogTracker. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_BlogTracker.
  • Page 654 The rest of the functionality resides in a custom class file, XmlMenu.as. You can find the sample source file, xmlmenu.fla, in the Samples folder on your hard disk. On Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.
  • Page 655 The server-side script that passes information between Flash and the database reads and writes the data in XML format. You can use ActionScript to convert information collected in the SWF file (for example, a user name and password) to an XML object and then send the data to the server-side script as an XML document.
  • Page 656 The following ActionScript is placed on the timeline and is used to send XML-formatted data to the server. To understand this script, read the commented lines (indicated by the characters // ignore XML white space XML.prototype.ignoreWhite = true; // Construct an XML object to hold the server's reply var loginReplyXML:XML = new XML();...
  • Page 657 loginXML.sendAndLoad("http://www.flash-mx.com/mm/main.cfm", loginReplyXML); You can test this code by using a user name of and the password . The JeanSmith VerySecret first section of the script generates the following XML when the user clicks the login button: <login username="JeanSmith" password="VerySecret" /> The server receives the XML, generates an XML response, and sends it back to the SWF file.
  • Page 658 ActionScript 2.0 Language Reference. This design is only an example, and Macromedia can make no claims about the level of security it provides. If you are implementing a secure password-protected system, make sure you have a good understanding of network security.
  • Page 659 The following example shows how you can use the XML class’s event handler onHTTPStatus to check whether an XML file successfully downloaded from the server and what the status code returned from the HTTP request was. Checking HTTP status codes using the XML class: Create a new Flash document and save it as xmlhttp.fla.
  • Page 660 One sample demonstrates how to create a web log tracker by loading, parsing, and manipulating XML data. You can find the sample source file, xml_blogTracker.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_BlogTracker. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_BlogTracker.
  • Page 661 Using the XMLSocket class ActionScript provides a built-in XMLSocket class, which lets you open a continuous connection with a server. A socket connection lets the server publish, or push, information to the client as soon as that information is available. Without a continuous connection, the server must wait for an HTTP request.
  • Page 662 The following example creates an XML socket connection and sends data from the XML object . To understand the script, read the commented lines (indicated by the characters myXML // Create XMLSocket object var theSocket:XMLSocket = new XMLSocket(); // Connect to a site on unused port above 1024 using connect() method. // Enter localhost or 127.0.0.1 for local testing.
  • Page 663: Sending Messages To And From Flash Player

    Flash Player To send messages from a SWF file to its host environment (for example, a web browser, a Macromedia Director movie, or the stand-alone Flash Player), you can use the fscommand() function.This function lets you extend your SWF file by using the capabilities of the host. For...
  • Page 664 The following table shows the values you can specify for the command arguments parameters of to control the playback and appearance of a SWF file playing in fscommand() the stand-alone player, including projectors. A projector is a SWF file saved in a format that can run as a stand-alone application—that is, embedding Flash Player with your content in an executable file.
  • Page 665 Flash when you republish. In a web browser, open the HTML file to view it. Click the Open Window button; a window is opened to the Macromedia website. Click the Alert button; an alert window appears. Sending messages to and from Flash Player...
  • Page 666 JavaScript methods and in Netscape 6.2 or later. For more FSCommand information, see the Macromedia Support Center article, “Scripting With Flash,” at www.macromedia.com/support/flash/publishexport/scriptingwithflash/. For Netscape 6.2 and later, you do not need to set the attribute to...
  • Page 667: About The External Api

    About the External API The ExternalInterface class is also called the External API, which is a new subsystem that lets you easily communicate from ActionScript and the Flash Player container to an HTML page with JavaScript or to a desktop application that embeds Flash Player. This functionality replaces the older function for interoperating with a HTML fscommand()
  • Page 668 The following sections contain examples that use the External API: “Creating interaction with the External API” on page 668 “Controlling Flash Video with the External API” on page 671 Creating interaction with the External API You can create interaction between the browser and a SWF file that’s embedded on a web page.
  • Page 669 The previous code is split into three sections. The first section imports the ExternalInterface class so you don’t have to use its fully qualified class name. The second section of code defines a callback function, , which is called from JavaScript in asFunc() an HTML document created in an upcoming example.
  • Page 670 This JavaScript code defines three methods. The first method returns a reference to the embedded SWF file based on whether the user’s browser is Microsoft Internet Explorer (IE) or a Mozilla browser. The second function, , calls the method makeCall() asFunc() that you defined within the Flash document in the previous example.
  • Page 671 You can find the sample source file, ExtInt.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\ExternalAPI\simple example. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/ExternalAPI/simple example. For a more complex example that uses the External API, see “Controlling Flash Video with...
  • Page 672 Add the following ActionScript to Frame 1 of the main Timeline: import flash.external.ExternalInterface; /* Register playVideo() and pauseResume() so that it is possible to call them from JavaScript in the container HTML page. */ ExternalInterface.addCallback("playVideo", null, playVideo); ExternalInterface.addCallback("pauseResume", null, pauseResume); /* The video requires a NetConnection and NetStream object.
  • Page 673 When you’re finished, go on to the next procedure to create the container for the SWF file. You can find the sample source file, external.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\ExternalAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/ExternalAPI.
  • Page 674 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>ExternalInterface</title> <script language="JavaScript"> // Use a variable to reference the embedded SWF file. var flashVideoPlayer; /* When the HTML page loads (through the onLoad event of the <body> tag), it calls the initialize() function.
  • Page 675 <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="video.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="video.swf" quality="high" bgcolor="#ffffff" width="320" height="240" name="videoPlayer" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> <form name="videoForm"> Select a video:<br /> <select name="videos"> <option value="lights_long.flv">lights_long.flv</option> <option value="clouds.flv">clouds.flv</option>...
  • Page 676 Flash plays the selected FLV file and updates the contents of the videoStatus text area within the HTML document. You can find the sample source file, external.fla, in the Samples folder on your hard disk. In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\ExternalAPI. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/ExternalAPI.
  • Page 677: Chapter 17: Understanding Security

    Flash Player 6, a SWF file that resides in www.macromedia.com could read data on a server located at data.macromedia.com; that is, Flash Player 6 allowed a SWF file from one domain to load data from a similar domain.
  • Page 678 SWF file’s domain, the Macromedia Flash Player Settings dialog box appears. The dialog box asks the user to allow or deny the cross-domain data access.
  • Page 679: About Local File Security And Flash Player

    About local file security and Flash Player Flash Player 8 has made enhancements to the security model, in which Flash applications and SWF files on a local computer are not allowed to communicate with both the Internet and the local file system by default. A local SWF file is a SWF file that is locally installed on a user’s computer, not served from a website, and does not include projector (EXE) files.
  • Page 680 681. For more information on security, see www.macromedia.com/devnet/security/ and www.macromedia.com/software/flashplayer/security/. Understanding local security sandboxes There are several different security sandboxes in the Flash Player. Each one determines how a SWF file can interact with the local file system, the network, or both the local file system and network at the same time.
  • Page 681 (remote or local). About Flash Player security settings Macromedia has designed Flash Player to provide security settings that do not require you to explicitly allow or deny access in most situations. You might occasionally encounter legacy Flash content that was created using older security rules for Flash Player 7 or earlier.
  • Page 682 Flash applications on your computer may communicate with the Internet. To change your security settings or learn more about your options, you use the Global Security Settings panel. Use this panel to reset the privacy settings in Macromedia Flash Player: If you select Always Deny and then confirm your selection, any website that tries to use your camera or microphone is denied access.
  • Page 683 Settings Manager” on page 688. For more information on the Global Security Settings panel, see www.macromedia.com/support/documentation/en/flashplayer/ help/settings_manager04a.html. The selections users make in the Global Security Settings panel override any decisions made in the security pop-up dialog box.
  • Page 684 Flash Player available for download from the Macromedia website. The Flash Player that’s embedded within the projector file might be a legacy version if the projector was created with an older version of Flash, or an edition of Flash Player was released after the current version of the Flash authoring tool.
  • Page 685 Republish and redeploy Republish the file with Flash Basic 8 or Flash Professional 8. The authoring tool requires you to specify in the Publish Settings dialog box whether a local SWF file can access the network or the local file system—but not both. If you specify that a local SWF file can access the network, you also must enable permissions for that SWF file (and all local SWF files) in the SWF, HTML, data, and/or server files that it accesses.
  • Page 686 Local SWF files SWF files that operate with local file systems or UNC network paths are placed into one of three sandboxes in Flash Player 8. By default, local SWF files are placed in the local-with-file-system sandbox. Local SWF files that are registered as trusted (using a configuration file) are placed in the local-trusted sandbox.
  • Page 687 Access network only To set this permission level, select Publish Settings > Flash, and then select Access Network Only from the Local Playback Security pop-up menu. Local SWF files with network access can read from a server if the server contains a cross-domain policy file with <allow-access- .
  • Page 688 Testing content locally with Flash 8 local file security restrictions As a Flash developer, you frequently test Flash applications locally, so you might see a dialog box prompt when a local Flash application tries to communicate with the Internet. You might see this dialog box when you test a SWF file in Flash Player if the SWF file does not have network access.
  • Page 689 The following example shows how to specify that a local SWF file can communicate with the Internet. When you test a file in a browser locally (File > Publish Preview > HTML), a security dialog box might appear. If you click Settings, the Settings Manager Global Security Settings panel appears To specify that a local SWF file can communicate with the Internet and local file system:...
  • Page 690 Flash Basic 8 and Flash Professional 8 authoring tool installs. The FlashAuthor.cfg file is located in the following approximate directories: Windows boot disk\Documents and Settings\<UserName>\Application Data\Macromedia\Flash Player\#Security Macintosh /Users/<UserName>/Library/Preferences/Macromedia/Flash Player/#Security/ By default, this file is set to , which means the warnings you...
  • Page 691 You might want to provide a FlashAuthor.cfg file, with set to LocalSecurityPrompt Author to other developers in your design or development process or to users who test Flash applications on their local hard disk and do not have the Flash 8 authoring tool installed. This helps you mimic the end user’s experience with your locally deployed content.
  • Page 692 SWF files to run on their local hard disks. For more information on configuration files, see www.macromedia.com/go/flashauthorcfg. You can also create a unique configuration file to trust one or more directories. For detailed information on security, see www.macromedia.com/devnet/security/and...
  • Page 693 localWithNetwork The SWF file is a local file that has not been trusted by the user, and was published with Access Network Only selected in the Publish Settings dialog box (Flash tab). The SWF file can communicate with the network but cannot read from local data sources.
  • Page 694: About Domains, Cross-Domain Security, And Swf Files

    (non-HTTPS) protocols cannot read content loaded through a secure (HTTPS) protocol, even when both are in exactly the same domain. For example, a SWF file located at http://www.macromedia.com/main.swf cannot load data from https://www.macromedia.com/data.txt without explicit permission; neither...
  • Page 695 (even if this domain resolves to 65.57.83.12) www.macromedia.com 65.57.83.12 (even if www.macromedia.com resolves to this IP address) Flash Player 8 does not allow local SWF files to communicate with the Internet without a proper configuration. For information on setting up a configuration file to test content locally, see “Creating configuration files for Flash development”...
  • Page 696 In Flash Player 7, exact-domain matching rules are used by default. That is, the settings and data for a file hosted at here.xyz.com are stored at here.xyz.com, the settings and data for a file hosted at there.xyz.com are stored at there.xyz.com, and so on. lets System.exactSettings you specify which rules to use.
  • Page 697 The following issue affects only SWF files published for Flash Player 7. When the receiver is HTTPS, and the sender is a local SWF file, is called, even though allowDomain() should be called. However, in Flash Player 8, when an HTTPS allowInsecureDomain() LocalConnection receiver is Flash Player 8, and the sender is a local file, is called.
  • Page 698 The opposite situation can also occur; that is, you might create a child SWF file that wants to allow its parent to script it, but doesn’t know what the domain of its parent SWF file will be (meaning, it’s a SWF file that might be loaded by a variety of domains). In this situation, call from the child SWF file.
  • Page 699 Because Flash Player 7 and later versions implement exact-domain matching rules instead of superdomain matching rules, you might have to modify existing scripts if you want to read them from files that are published for Flash Player 7 or 8. (You can still publish the modified files for Flash Player 6.) If you used any LocalConnection.allowDomain() statements in your files and specified superdomain sites...
  • Page 700 The SWF files are not in the same domain (for example, one file is at www.domain.com and one is at store.domain.com). You must make the following changes: If the called SWF file is published for Flash Player 7 or later, include in the called SWF System.security.allowDomain LocalConnection.allowDomain...
  • Page 701 (security.allowDomain method) in the ActionScript 2.0 Language Reference. For example, suppose main.swf is served from www.macromedia.com. That SWF file then loads another SWF file (data.swf ) from data.macromedia.com into a movie clip instance that’s created dynamically using createEmptyMovieClip() // In macromedia.swf...
  • Page 702: Server-Side Policy Files For Permitting Access To Data

    XML.load() XML.sendAndLoad() LoadVars.load() LoadVars.sendAndLoad() loadVariables() loadVariablesNum(), , and Macromedia Flash Remoting MovieClip.loadVariables() XMLSocket.connect() ). Also, a SWF file can import runtime shared NetServices.createGatewayConnection libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL must reside in the same domain as the SWF file that is loading that external data or media.
  • Page 703 For example, a policy file located at https://www.macromedia.com:8080/crossdomain.xml applies only to data loading calls made to www.macromedia.com over HTTPS at port 8080. An exception to this rule is the use of an XMLSocket object to connect to a socket server in another domain.
  • Page 704 If the SWF file you are downloading comes from an HTTPS server, but the SWF file loading it is on an HTTP server, you need to add the attribute to the secure="false" <allow- tag, as shown in the following code: access-from>...
  • Page 705 If you want to use a policy file in a custom location on the server, you must call before you make any requests that depend on the policy System.security.loadPolicyFile file, such as the following: System.security.loadPolicyFile("http://www.foo.com/folder1/folder2/ crossdomain.xml"); var my_xml:XML = new XML(); my_xml.load("http://www.foo.com/folder1/folder2/myData.xml");...
  • Page 706 In this example, Flash Player tries to retrieve a policy file from the specified host and a port. Any port can be used if the policy file is not in the default (root) directory; otherwise the port is limited to 1024 and higher (as with earlier players). When a connection is established to the specified port, Flash Player sends , terminated by a null byte.
  • Page 707: Http To Https Protocol Access Between Swf Files

    HTTP to HTTPS protocol access between SWF files You must use an handler or method to permit a SWF file in one domain to be allowDomain accessed by a SWF file in another domain. However, if the SWF file being accessed is hosted at a site that uses a secure protocol (HTTPS), the handler or method doesn’t allowDomain...
  • Page 708 The following code shows an example of the changes you might have to make: // Commands in a Flash Player 6 SWF file at https://www.someSite.com // to allow access by Flash Player 7 SWF files that are hosted // at http://www.someSite.com or at http://www.someOtherSite.com System.security.allowDomain("someOtherSite.com");...
  • Page 709 If the called file is published for Flash Player 6 and you want to port the called file to Flash Player 7, include System.security.allowInsecureDomain in the called file, using exact domain-name LocalConnection.allowInsecureDomain matching, as shown in the code examples earlier in this section. If the called file is published for Flash Player 5 or earlier, and both files are not in the same domain, you can do one of two things.
  • Page 710 Understanding Security...
  • Page 711: Chapter 18: Debugging Applications

    CHAPTER 18 Debugging Applications Macromedia Flash Basic 8 and Macromedia Flash Professional 8 provide several tools for testing ActionScript in your SWF files. The Debugger lets you find errors in a SWF file while it’s running in the Flash Debug Player (see “Debugging your scripts”...
  • Page 712 When you use the Control > Test Movie command to test SWF files that implement keyboard controls (tabbing, keyboard shortcuts created using , and so Key.addListener() on), select Control > Disable Keyboard Shortcuts. Selecting this option prevents the authoring environment from “grabbing” keystrokes, and lets them pass through to the player. For example, in the authoring environment, Control+U opens the Preferences dialog box.
  • Page 713 To activate the Debugger in test mode: Select Control > Debug Movie. This command exports the SWF file with debugging information (the SWD file) and enables debugging of the SWF file. It opens the Debugger and opens the SWF file in test mode.
  • Page 714 Debugging a SWF file from a remote location You can debug a remote SWF file by using the stand-alone, ActiveX, or plug-in version of Flash Player. To find these versions of Flash Player, look in the following directory in Windows or Macintosh: Flash install directory\Players\Debug\. When you export a SWF file, you can enable debugging in the file and create a debugging password.
  • Page 715 In Flash, select Window > Debugger. In the Debugger, select Enable Remote Debugging from the pop-up menu (at the upper right of the panel). To activate the Debugger from a remote location: Open the Flash authoring application. In a browser or in the debug version of the stand-alone player, open the published SWF file from the remote location.
  • Page 716 When a connection is established, a password prompt appears. Enter your debugging password if you set one. The display list of the SWF file appears in the Debugger. If the SWF file doesn’t play, the Debugger might be paused, so click Continue to start it. Displaying and modifying variables The Variables tab in the Debugger shows the names and values of any global and timeline variables in the SWF file that are selected in the display list.
  • Page 717 , or "Hello" 3523 "http:// , and you cannot use . The value can be www.macromedia.com" x + 2 eval("name:" +i) a string (any value surrounded by quotation marks [""]), a number, or a Boolean value ( true false To write the value of an expression to the Output panel in test mode, use the trace statement.
  • Page 718 If you add a local variable to the Watch list, its value appears only when Flash Player is stopped at a line of ActionScript where that variable is in scope. All other variables appear while the SWF file is playing. If the Debugger can’t find the value of the variable, the value is listed as undefined.
  • Page 719 Displaying movie clip properties and changing editable properties The Debugger’s Properties tab shows all the property values of any movie clip on the Stage. You can change a value and see its effect in the SWF file while it runs. Some movie clip properties are read-only and cannot be changed.
  • Page 720 To modify a property value: Double-click the value, and enter a new value. The value cannot be an expression. For example, you can enter 50 or "clearwater", but you cannot enter x + 50. The value can be a string (any value surrounded by quotation marks [""]), a number, or a Boolean value ( ).
  • Page 721 When you work with breakpoints in an external script file in the Script window, the AsBreakpoints.xml file lets you store breakpoint information. The AsBreakpoints.xml file is written to the Local Settings directory, in the following locations: Windows: Hard Disk\Documents and Settings\User\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Debugger\ Macintosh: Macintosh HD/Users/User/Library/Application Support/Macromedia Flash 8/Configuration/...
  • Page 722 An example of the AsBreakpoints.xml is as follows: <?xml version="1.0"?> <flash_breakpoints version="1.0"> <file name="c:\tmp\myscript.as"> <breakpoint line="10"></breakpoint> <breakpoint line="8"></breakpoint> <breakpoint line="6"></breakpoint> </file> <file name="c:\tmp\myotherscript.as"> <breakpoint line="11"></breakpoint> <breakpoint line="7"></breakpoint> <breakpoint line="4"></breakpoint> </file> </flash_breakpoints> The XML file consists of the following tags: flash_breakpoints This node has an attribute, called , that indicates the version of version...
  • Page 723 When you click the button, the breakpoint is reached and Flash Player pauses. You can now bring the Debugger to the first line of wherever it is defined in the document. myFunction() You can also continue through or exit out of the function. As you step through lines of code, the values of variables and properties change in the Watch list and in the Variables, Locals, and Properties tabs.
  • Page 724: Using The Output Panel

    Step Out advances the Debugger out of a function. This button works only if you are currently stopped in a user-defined function; it moves the yellow arrow to the line after the line where that function was called. In the previous example, if you place a breakpoint at line 3 and click Step Out, the Debugger moves to line 8.
  • Page 725 To work with the contents of the Output panel, click the pop-up menu in the upper right corner to see your options. The following table lists the options available on the Output panel’s pop-up menu: Menu item What it does Word wrap Toggles whether long lines wrap automatically, so the user does not have to use the horizontal scroll bar to view the entire line of...
  • Page 726 For more information on the Output panel, see the following topics: “Listing a SWF file’s objects” on page 726 “Listing a SWF file’s variables” on page 727 “About displaying text field properties for debugging” on page 728 “Using the trace statement” on page 728 “Updating Flash Player for testing”...
  • Page 727 Listing a SWF file’s variables In test mode, the List Variables command shows a list of all the variables currently in the SWF file. This list is especially useful for finding the correct variable target path and variable name. Unlike the Debugger, the list does not update automatically as the SWF file plays; you must select the List Variables command each time you want to send the information to the Output panel.
  • Page 728 About displaying text field properties for debugging To obtain debugging information about TextField objects, you can use the Debug > List Variables command in test mode. The Output panel uses the following conventions to show TextField objects: If a property is not found on the object, it does not appear. No more than four properties appear on a line.
  • Page 729 Select Control > Test Movie to test the SWF file. The Output panel displays the following message: Updating Flash Player for testing You can download the latest version of Flash Player from the Macromedia Support Center at www.macromedia.com/support/flash and use it to test your SWF files.
  • Page 730 Debugging Applications...
  • Page 731: Chapter 19: Best Practices And Coding Conventions For Actionscript 2.0

    Best Practices and Coding Conventions for ActionScript 2.0 Macromedia Flash designers and developers must write code and structure applications in a way that is intuitive and beneficial to themselves as well as to the other people who are working on the same project. This is particularly important in FLA files with lots of assets, or long code files.
  • Page 732: Naming Conventions

    When you are learning or teaching Flash and ActionScript Learning how to build applications by using best practices and following coding conventions reduces the need to relearn particular methodologies. If students learning Flash practice consistent and better ways to structure code, they might learn the language more quickly and with less frustration.
  • Page 733 Using naming conventions for your variable names can serve the following important functions: They make your code readable so that you can immediately identify a variable’s data type. This can help students, those learning code, or developers unfamiliar with your code. They are easy to search for and replace when necessary.
  • Page 734 General naming guidelines This section reviews naming guidelines for writing ActionScript code. Naming conventions are important for writing logical code. The primary purpose is to improve the readability of your ActionScript 2.0 code. Remember that all variables must have unique names. Names are case-sensitive in Flash Player 7 and later.
  • Page 735 The following table lists reserved keywords in ActionScript 2.0 that cause errors in your scripts when used as variable names: break case catch class continue default delete dynamic else extends false finally function ifFrameLoaded implements import instanceof interface intrinsic null onClipEvent private public...
  • Page 736 Naming variables Variable names can only contain letters, numbers, and dollar signs ( ). Do not begin variable names with numbers. Variables must be unique and they are case-sensitive in Flash Player 7 and later. For example, avoid the following variable names: my/warthog = true;...
  • Page 737 Don’t use variables that are parts of common programming constructs. Don’t use language constructs if you are aware of them in other programming languages, even if Flash does not include or support these language constructs. For example, do not use the following keywords as variables: textfield = "myTextField";...
  • Page 738 (variables that do not change): Constants should be uppercase. Separate words should contain underscores. You can see these guidelines at work in the following ActionScript code snippet: var BASE_URL:String = "http://www.macromedia.com"; // constant var MAX_WIDTH:Number = 10; // constant...
  • Page 739 Naming functions and methods Use the following guidelines when you name functions and methods in your code. For information on writing functions and methods, see Chapter 6, “Functions and Methods.” Use descriptive names. Use mixed case for concatenated words. A good example would be singLoud() Start function and method names with a lowercase letter.
  • Page 740 The following guidelines apply to naming classes: Begin a class name with an uppercase letter. Write class names in mixed case when it’s a compound or concatenated word. Begin with an uppercase letter for a compound or concatenated word. A good example is NewMember Class names are usually nouns or qualified nouns.
  • Page 741 Naming packages It’s common for package names to use “reverse domain” naming convention. Examples of reverse domain names include for macromedia.com, and com.macromedia org.yourdomain for yourdomain.org. Use the following guidelines when you name packages: Put the prefix for a package name in all lowercase letters.
  • Page 742: Using Comments In Your Code

    If you develop custom components, use a naming convention to prevent naming incompatibilities with Macromedia components. The names of your components must be different from those of the default set that is included with Flash. If you adopt your own consistent naming convention, it helps you prevent naming conflicts.
  • Page 743 For more information on writing comments in your ActionScript code, see the following sections: “Writing good comments” on page 743 “Adding comments to classes” on page 744 Writing good comments Using comments consistently in your ActionScript 2.0 code allows you to describe complex areas of code or important interactions that are not otherwise clear.
  • Page 744 Start classes with a standard comment, which uses the following format: User class version 1.2 3/21/2004 copyright Macromedia, Inc. After the documentation comments, declare the class. Implementation comments should directly follow the declaration. Don’t include comments that do not directly relate to the class that’s being read. For example, don’t include comments that describe the corresponding package.
  • Page 745: Actionscript Coding Conventions

    Use block, single-line, and trailing comments within the body of your class to comment on your ActionScript code. For more information on using comments in class files, see “Adding comments to classes” on page 744. ActionScript coding conventions One of the most important aspects about programming is consistency, whether it relates to variable naming schemes (covered in “Naming conventions”...
  • Page 746 One of the most difficult parts of debugging a FLA file is finding all the code. After you find all the code, you must figure out how it interacts with other pieces of code along with the FLA file. If you put all your code in a single frame, it is much easier to debug because it is centralized, and these problems occur less frequently.
  • Page 747 However, placing the equivalent ActionScript code on a timeline appears as follows: // good code myBtn.onRelease = function() { // Do something. For more information on ActionScript syntax, see “Formatting ActionScript syntax” on page 764. Using behaviors and screens sometimes involves attaching code to objects, so different practices apply when you use these features.
  • Page 748 Avoiding absolute targets (_root) You can use several methods to target instances that let you avoid using ; these methods _root are discussed later in this section. Avoid using in ActionScript 2.0 because SWF files _root that load into other SWF files might not work correctly. The identifier targets the base _root SWF file that is loading, not the SWF file using relative addressing instead of...
  • Page 749 Using the this keyword Whenever possible, use the keyword as a prefix instead of omitting the keyword, even if this your code works without it. Use the keyword to learn when a method or property this belongs to a particular class. For example, for a function on a timeline, you write ActionScript 2.0 code by using the following format: circleClip.onPress = function() { this.startDrag();...
  • Page 750 About scope in classes When you port code to ActionScript 2.0 classes, you might have to change how you use the keyword. For example, if you have a class method that uses a callback function (such as this the LoadVars class’s method), it can be difficult to know if the keyword refers to onLoad...
  • Page 751 Structuring a class file You create classes in separate ActionScript 2.0 files that are imported into a SWF file when it is compiled. You create classes in separate ActionScript 2.0 files that are imported into a SWF file when you compile an application. To create a class file, you write code that can have a certain methodology and ordering.
  • Page 752 Guidelines for creating a class Remember the following guidelines when you create a class file: Place only one declaration per line. Don’t place multiple declarations on a single line. For example, format your declarations as shown in the following example: var prodSkuNum:Number;...
  • Page 753 Widget() { Widget.widgetCount++; You don’t have to add these prefixes, and some developers feel it is unnecessary. Macromedia recommends that you add the keyword as a prefix, because it can this improve readability and it helps you write clean code by providing context.
  • Page 754 About initialization For the initial values for variables, assign a default value or allow the value of , as undefined the following class example shows. When you initialize properties inline, the expression on the right side of an assignment must be a compile-time constant. That is, the expression cannot refer to anything that is set or defined at runtime.
  • Page 755 One of the easiest ways to initialize code by using ActionScript 2.0 is to use classes. You can encapsulate all your initialization for an instance within the class’s constructor function, or abstract it into a separate method, which you would explicitly call after the variable is created, as the following code shows: class Product { function Product() {...
  • Page 756 Use trace statements statements in your documents to help you debug your code while authoring the trace FLA file. For example, by using a statement and loop, you can see the values of trace variables in the Output panel, such as strings, arrays, and objects, as the following example shows: var dayArr:Array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];...
  • Page 757 About the super prefix If you refer to a method in the parent class, prefix the method with so that other super developers know from where the method is invoked. The following ActionScript 2.0 snippet demonstrates the use of proper scoping by using the prefix: super In the following example, you create two classes.
  • Page 758 Then create a new AS or FLA file and enter the following ActionScript in the document: import Socks; var mySock:Socks = new Socks("maroon"); trace(" -> "+mySock.getColor()); mySock.setColor("Orange"); trace(" -> "+mySock.getColor()); The following result is displayed in the Output panel: [Clothes] I am the constructor [Socks] I am the constructor [Socks] I am getColor [Clothes] I am getColor...
  • Page 759 In this code, you attach a movie clip instance from the library and use the statement to with modify its properties. When you do not specify a variable’s scope, you do not always know where you are setting properties, so your code can be confusing. In the previous code, you might expect to be set within the movie clip, but it is actually...
  • Page 760 About using functions Reuse blocks of code whenever possible. One way you can reuse code is by calling a function multiple times, instead of creating different code each time. Functions can be generic pieces of code; therefore, you can use the same blocks of code for slightly different purposes in a SWF file.
  • Page 761 The following example puts functions into a class file. This is a best practice when you choose to use ActionScript 2.0, because it maximizes code reusability. To reuse the functions in other applications, import the existing class rather than rewrite the code from scratch, or duplicate the functions in the new application.
  • Page 762: Actionscript And Flash Player Optimization

    About stopping code repetition event handler is useful because Flash can use it to repeat code at the frame onEnterFrame rate of a SWF file. However, limit the amount of repetition that you use in a Flash file as much as possible so that you do not affect performance. For example, if you have a piece of code that repeats whenever the playhead enters a frame, it is processor intensive.
  • Page 763 Optimizing your code Remember the following guidelines when you optimize your code: Avoid calling a function multiple times from within a loop. It is better to include the contents of a small function inside the loop. Use native functions when possible. Native functions are faster than user-defined functions.
  • Page 764: Formatting Actionscript Syntax

    Formatting ActionScript syntax Formatting ActionScript 2.0 code in a standardized way is essential to writing maintainable code, and it’s easier for other developers to understand and modify. For example, it would be extremely difficult to follow the logic of a FLA file that has no indenting or comments, as well as inconsistent naming conventions and formatting.
  • Page 765 Macromedia recommends the following formatting points to help promote readability in your ActionScript code. Put one blank line between paragraphs (modules) of ActionScript. Paragraphs of ActionScript code are groups of logically related code. Adding a blank line between them helps users read the ActionScript code and understand its logic.
  • Page 766 Use spaces to separate all operators and their operands. Using spaces makes it is easier to distinguish between method calls and keywords, as the following example shows: //good var sum:Number = 7 + 3; //bad var sum:Number=7+3; An exception to this guideline is the dot ( ) operator.
  • Page 767 Align the second line with the start of the expression on the previous line of code. You can control auto-indentation and indentation settings by selecting Edit > Preferences (Windows) or Flash > Preferences (Macintosh), and then selecting the ActionScript tab. Writing conditional statements Use the following guidelines when you write conditional statements: Place conditions on separate lines in...
  • Page 768 You can write a conditional statement that returns a Boolean value in two ways. The second example is preferable: if (cartArr.length>0) { return true; } else { return false; Compare this example with the previous one: // better return (cartArr.length > 0); The second snippet is shorter and has fewer expressions to evaluate.
  • Page 769 Place braces around each statement when it is part of a control structure ( if..else even if it contains only a single statement. The following example shows code that is written poorly: // bad if (numUsers == 0) trace("no users found."); Although this code validates, it is poorly written because it lacks braces around the statements.
  • Page 770 Writing while and do..while statements You can write statements using the following format: while while (condition) { // statements You can write statements using the following format: do-while do { // statements } while (condition); Writing return statements Don’t use parentheses [()] with any return statements that have values. The only time to use parentheses with statements is when they make the value more obvious, as shown in return...
  • Page 771 You can write statements using the following format: switch switch (condition) { case A : // statements // falls through case B : // statements break; case Z : // statements break; default : // statements break; Writing try..catch and try..catch..finally statements Write statements using the following formats: try..catch...
  • Page 772 A slight variation on the first example in this section is to use the method, but handleEvent this technique is slightly more cumbersome. Macromedia does not recommend this technique because you must use a series of statements or a statement to detect which if..else...
  • Page 773: Appendix A: Error Messages

    APPENDIX A Error Messages Macromedia Flash Basic 8 and Macromedia Flash Professional 8 provide compile-time error reporting when you publish to ActionScript 2.0 (the default). The following table contains a list of error messages that the Flash compiler can generate:...
  • Page 774 Error Message text number 1112 A class may not extend itself. 1113 An interface may not extend itself. 1114 There is no interface defined with this name. 1115 A class may not extend an interface. 1116 An interface may not extend a class. 1117 An interface name is expected after the ‘implements’...
  • Page 775 Error Message text number 1141 The name of this class, ‘<A.B.C>’, conflicts with the name of another class that was loaded, ‘<A.B>’. (This error occurs when the ActionScript 2.0 compiler cannot compile a class because of the full name of an existing class is part of the conflicting class' name.
  • Page 776 Error Message text number 1166 The class being compiled, ‘<A.b>’, does not match the class that was imported, ‘<A.B>’. (This error occurs when a class name is spelled with a different case from an imported class. For example, compiling class generates error mx.com.util 1166 if the statement...
  • Page 777 Error Message text number 1188 Import statements are not allowed inside class or interface definitions. 1189 The class ‘<A.B>’ cannot be imported because its leaf name is already resolved to the class that is being defined, ‘<C.B>’. (For example, compiling class generates error 1189 if the statement util appears in the util.as file.)
  • Page 778 Error Message text number 1206 Member function '<functionName>' is larger than 32K. 1207 Anonymous function around line <lineNumber> exceeds 32K span. 1208 Code around line <lineNumber> exceeds 32K span. 1210 The package name '<PackageName>' cannot also be used as a method name. 1211 The package name '<PackageName>' cannot also be used as a property name.
  • Page 779: Appendix B: Deprecated Flash 4 Operators

    APPENDIX B Deprecated Flash 4 operators The following table lists Flash 4–only operators, which are deprecated in ActionScript 2.0. Do not use these operators unless you are publishing to Flash Player 4 and earlier. Operator Description Associativity Logical NOT Right to left Logical AND Left to right Logical OR (Flash 4)
  • Page 780 Deprecated Flash 4 operators...
  • Page 781: Appendix C: Keyboard Keys And Key Code Values

    APPENDIX C Keyboard Keys and Key Code Values The following tables list all the keys on a standard keyboard and the corresponding key code values and ASCII key code values that are used to identify the keys in ActionScript: “Letters A to Z and standard numbers 0 to 9” on page 781 “Keys on the numeric keypad”...
  • Page 782 Letter or number key Key code ASCII key code Keyboard Keys and Key Code Values...
  • Page 783 Letter or number key Key code ASCII key code...
  • Page 784 Keys on the numeric keypad The following table lists the keys on a numeric keypad, with the corresponding key code values that are used to identify the keys in ActionScript: Numeric keypad key Key code ASCII key code Numpad 0 Numpad 1 Numpad 2 Numpad 3...
  • Page 785 Function key Key code ASCII key code This key is reserved by the This key is reserved by the system and cannot be used in system and cannot be used in ActionScript. ActionScript. Other keys The following table lists keys on a standard keyboard other than letters, numbers, numeric keypad keys, or function keys, with the corresponding key code values that are used to identify the keys in ActionScript: Key code...
  • Page 786 Key code ASCII key code Left Arrow Up Arrow Right Arrow Down Arrow Insert Delete Num Lock ScrLk Pause/Break " ' For additional key code and ASCII values, use the ActionScript at the beginning of this appendix and press the desired key to trace its key code. Keyboard Keys and Key Code Values...
  • Page 787: Appendix D: Writing Scripts For Earlier Versions Of Flash Player

    ActionScript has changed considerably with each release of the Macromedia Flash authoring tools and Flash Player. When you create content for Macromedia Flash Player 8, you can use the full power of ActionScript. You can still use Flash 8 to create content for earlier versions of Flash Player, but you can’t use every ActionScript element.
  • Page 788: Using Flash 8 To Create Content For Flash Player 4

    Using Flash 8 to create content for Flash Player 4 To use Flash 8 to create content for Flash Player 4, specify Flash Player 4 on the Flash tab of the Publish Settings dialog box (File > Publish Settings). Flash Player 4 ActionScript has only one basic primitive data type, which is used for numeric and string manipulation.
  • Page 789 operator in Flash 4 was used for numeric equality. In Flash 5 and later, is the equality operator and is the assignment operator. Any operators in Flash 4 files are automatically converted to Flash automatically performs type conversions to ensure that operators behave as expected.
  • Page 790 Using slash syntax Slash syntax ( ) was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. In slash syntax, slashes are used instead of dots and variables are preceded with a colon, as shown in the following example: myMovieClip/childMovieClip:myVariable To write the same target path in dot syntax, which is supported by Flash Player 5 and later versions, use the following syntax:...
  • Page 791: Actionscript 1.0

    APPENDIX E Object-Oriented Programming with ActionScript 1.0 The information in this appendix comes from the Macromedia Flash MX documentation and provides information on using the ActionScript 1.0 object model to write scripts. It is included here for the following reasons: If you want to write object-oriented scripts that support Flash Player 5, you must use ActionScript 1.0.
  • Page 792: About Actionscript 1.0

    About ActionScript 1.0 Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Chapter 7, “Classes,” on page 225. ActionScript is an object-oriented programming language. Object-oriented programming uses objects, or data structures, to group together properties and methods that control the object’s behavior or appearance.
  • Page 793 In this example, you create a function that needs two pieces of information, or parameters, to do its job: . When you call the function to create new instances of the object, you pass it the parameters. The following code creates instances of the object Biker called emma , and it traces the speed of the instance, using the...
  • Page 794: Creating A Custom Object In Actionscript 1.0

    Creating a custom object in ActionScript 1.0 Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Chapter 7, “Classes,” on page 225. To create a custom object, you define a constructor function. A constructor function is always given the same name as the type of object it creates.
  • Page 795: Assigning Methods To A Custom Object In Actionscript 1.0

    Assigning methods to a custom object in ActionScript 1.0 Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Chapter 7, “Classes,” on page 225. You can define the methods of an object inside the object’s constructor function. However, this technique is not recommended because it defines the method every time you use the constructor function.
  • Page 796: Defining Event Handler Methods In Actionscript 1.0

    To assign a method to a custom object: Define the constructor function Circle() function Circle(radius) { this.radius = radius; Define the method of the Circle object. The method calculates the getArea() getArea() area of the circle. In the following example, you can use a function literal to define the method and assign the property to the circle’s prototype object: getArea()
  • Page 797 To define an event handler method in an object’s prototype object: Create a movie clip symbol and set the linkage identifier to by selecting the symbol theID in the Library panel and selecting Linkage from the Library pop-up menu. In the Actions panel (Window > Actions), use the statement to define a new function class, as shown in the following example:...
  • Page 798: Creating Inheritance In Actionscript 1.0

    This step registers the symbol whose linkage identifier is with the class theID . All instances of have event handler methods that behave as myClipClass myClipClass defined in step 4. They also behave the same as all instances of the MovieClip class because you told the new class to inherit from the class MovieClip in step 3.
  • Page 799 All constructor functions have a property that is created automatically when the prototype function is defined. The property indicates the default property values for objects prototype created with that function. You can use the property to assign properties and prototype methods to a class.
  • Page 800: Adding Getter/Setter Properties To Objects In Actionscript 1.0

    Adding getter/setter properties to objects in ActionScript 1.0 Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Chapter 7, “Classes,” on page 225. You can create getter/setter properties for an object using the Object.addProperty() method.
  • Page 801: Using Function Object Properties In Actionscript 1.0

    Using Function object properties in ActionScript 1.0 Many Flash users can greatly benefit from using ActionScript 2.0, especially with complex applications. For information on using ActionScript 2.0, see Chapter 7, “Classes,” on page 225. You can specify the object to which a function is applied and the parameter values that are passed to the function, using the methods of the Function object.
  • Page 802 To invoke a function using the Function.call() method: Use the following syntax: myFunction.call(thisObject, parameter1, ..., parameterN) The method takes the following parameters: The parameter specifies the value of within the function body. thisObject this The parameters specify parameters to be passed to parameter1..., parameterN .
  • Page 803: Appendix F: Terminology

    APPENDIX F Terminology As with all scripting languages, ActionScript uses its own terminology. Macromedia Flash also uses unique terminology. The following list provides an introduction to important ActionScript terms, and Flash terms that relate to programming with ActionScript and that are unique to working in the Flash authoring environment.
  • Page 804 Caching refers to information that is reused in your application, or information that is stored on your computer so it can be reused. For example, if you download an image from the internet, it’s often cached so you can view it again without downloading the image data. Callback functions are anonymous functions that you associate with a certain event.
  • Page 805 Data types describe the kind of information a variable or ActionScript element can contain. The built-in ActionScript data types are String, Number, Boolean, Object, MovieClip, Function, null, and undefined. For more information, see “About data types” on page Device fonts are special fonts in Flash that are not embedded in a Flash SWF file.
  • Page 806 Functions are blocks of reusable code that can be passed parameters and can return a value. For more information, see “About functions and methods” on page 201. Function literals are unnamed functions that you declare in an expression instead of in a statement.
  • Page 807 Methods are functions associated with a class. For example, is a built-in method sortOn() associated with the Array class. You can also create functions that act as methods, either for objects based on built-in classes or for objects based on classes that you create. For example, in the following code, becomes a method of a object that you have...
  • Page 808 Parameters (also called arguments) are placeholders that let you pass values to functions. For example, the following function uses two values it receives in the parameters welcome() firstName hobby function welcome(firstName:String, hobby:String):String { var welcomeText:String = "Hello, " + firstName + ". I see you enjoy " + hobby +".";...
  • Page 809 String is a sequence of characters, and a data type. See “About strings and the String class” on page 450 for more information. String literal is a sequence of characters enclosed by straight quote characters. The characters are themselves a data value, not a reference to data. A string literal is not a String object. For more information, see “About strings and the String class”...
  • Page 810 Variables are identifiers that hold values of any data type. Variables can be created, changed, and updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables: var x:Number = 5;...
  • Page 811: Index

    Index Symbols ActionScript about 67, 68 \" 460 comparing versions 69 \’ 460 creating cue points with 615 \b 460 editing preferences 42 \f 460 Flash Player 762 \n 460 formatting 50 \r 460 publish settings 62 \t 460 ActionScript 2.0 \unnnn 460 assigning ActionScript 2.0 class to movie clips 378 \xnn 460...
  • Page 812 animations multidimensional using a for loop 170 continuing 493 pass by reference 95 that run continuously 494 referencing and finding length 167 anonymous function shorthand syntax 163 defined 803 to create object 109 using 210 using 164 writing 208 using shorthand syntax to create 90 anti-alias ASCII values 569 defined 803...
  • Page 813 bindings creating a one-way binding 580 cacheAsBitmap property 370 creating a two-way binding 582 caching, defined 804 creating with ActionScript 580 callback functions bitmap defined 804 graphics 803 writing 208 text 408 calling methods 76 bitmap caching caps styles about 369, 480 about 548 advantages and disadvantages 371 setting 548...
  • Page 814 classes preloading 299 about built-in 227 private methods and properties 248 accessing built-in properties 297 properties of 247 and ASO files 282 public, private, and static methods and properties and constructor functions 268 and inheritance 301 resolving class references 243 and instance variables 272 scoping 750 and polymorphism 308...
  • Page 815 collisions, detecting 576 convolution filter between movie clip and Stage point 577 about 527 between movie clips 577 about applying 527 color matrix filter using 528 about 525 counters, repeating action with 154, 155 using 475, 525 creating objects 296 colors creating strings 458 in Actions toolbox 51...
  • Page 816 converting 72 determining next available 367 defined 72, 805 managing 366 determining type 85 design patterns MovieClip 76 encapsulation 261 null 77 Singleton 252 Number 78 detecting collisions 576 Object 78 device fonts primitive 73 defined 408, 805 String 79 masking 377 undefined 80 displacement map filter...
  • Page 817 event model for event handler methods 330 easing for event listeners 333 about 488 for on() and onClipEvent() handlers 337 defining 482 events with code 490 and movie clips 378 ECMA-262 specification 115 broadcasting 342 effects defined 329, 805 blending modes 538 exporting scripts and language encoding 57 brightness 525 expressions...
  • Page 818 filters FlashType adjusting properties 530 about 406 and ActionScript 505 Flash Player support 406 and error handling 504 FlashVars and memory usage 504 about 392 and out-of-memory error 504 using to display text 393 and performance 504 FlashVars property and transparency 505 about 392 animating 532 using 104...
  • Page 819 for..in loops 158 named function syntax 202 form feed character 460 naming 214 formatting code 50, 51 nested 222 formatting text passing parameters to 218 using 415 returning values from 220 frame rate reusing 214 about 471 sample 808 and onEnterFrame 471 standard format for named functions 207 choosing 471 targeting and calling user-defined functions 213...
  • Page 820 gradient glow filter importing about 515 class files 239 using 516 scripts, and language encoding 57 grayscale image 475 indentation in code, enabling 51 grid fit types, using 417 indexed array 164, 169 information, passing between SWF files 634 inheritance about 301 and OOP 232 handlers.
  • Page 821 miterLimit 554 parameters 549 JavaScript pixelHinting 551 alert statement 728 scaling 551 and ActionScript 115 stroke and cap styles 548 and Netscape 666 thickness 549 international standard 115 lines 548 sending messages to 664 linkage JPEG files coding conventions 742 embedding in text fields 445 identifier 362, 378 loading into movie clips 357, 593...
  • Page 822 351 controlling 352 Macromedia Director, communicating with 666 creating an empty instance 360 manipulating numbers 78 creating at runtime 360 masks 376 creating subclasses 378 and alpha channel masking 377 data type 76 and device fonts 377 deleting 362...
  • Page 823 loading into movie clips 598 data type 78 preloading 599, 609 defined 807 reading ID3 tags 601 fading out 472 multidimensional arrays, about 169 looping through children of 155 multiple languages, using in scripts 57 organizing data in arrays 109 old players, targeting 787 on() and onClipEvent() handlers 337 attaching to movie clips 338...
  • Page 824 relational and equality 190 policy files unary 186 defined 702 using assignment 194 must be named crossdomain.xml 702 using in Flash 199 See also security using with strings 182 polymorphism order of execution (operator) about 234 operator associativity 179 using 308 operator precedence 179 post colon syntax, defined 82 organizing scripts...
  • Page 825 reserved words moving objects 477 about 139 panning images 478 built-in class names 140 Tween and TransitionManager classes 481 future reserved words 139 scripts listed 139 about events 32 other recommendations 140 clip events 33 See also keywords correcting text display problems 57 resources, additional 14 debugging 711 return statement 770...
  • Page 826 slash syntax comparing to other data types 463 about 124 converting and concatenating 464 not supported in ActionScript 2.0 124 converting case 464 using 790 creating 458 socket connections creating an array of substrings 466 about 661 defined 451, 809 sample script 662 determining length 460 sounds...
  • Page 827 syntax controlling embedded media 447 case sensitivity 117 creating dynamically at runtime 386, 387 checking 55 default properties 421 slash 124 defined 809 syntax color options, setting in the Actions panel 52 displaying properties for debugging 728 system dynamic 383 event, defined 329 embedding clickable images in 449 requirements, for ActionScript 2.0 10...
  • Page 828 transferring variables between movie and server 640 Universal Character Set (UCS) 451 Transition class unpinning scripts in the Actions panel 60 animating brightness level 526 URL variables, about 101 TransitionManager class URL-encoded format, sending information 634 about 481 user event 329 and easing 482 user-defined functions using 485...
  • Page 829 variables, global 97 vector graphics 810 XLIFF files 453 video XML 652 about 603 DOM 653 about external FLV files 604 example of using with styles 434 adding seek functionality 617 hierarchy 653 and Macintosh 624 in server-side scripts 655 configuring the server for FLV 623 loading and displaying text 397 creating a banner 607...
  • Page 830 Index...

This manual is also suitable for:

Flash 8

Table of Contents