background image

Learning ActionScript 2.0 in Flash

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

Page 1: ...Learning ActionScript 2 0 in Flash...

Page 2: ...l rights reserved Macromedia Flash 8 video is powered by On2 TrueMotion video technology 1992 2005 On2 Technologies Inc All Rights Reserved http www on2 com Visual SourceSafe is a registered trademark...

Page 3: ...Organizing ActionScript code 33 Using the Actions panel and Script window 35 About the Actions panel 36 About the Script window 37 About coding in the Actions panel and Script window 38 About Actions...

Page 4: ...About working with custom classes in an application 238 Example Writing custom classes 263 Example Using custom class files in Flash 276 Assigning a class to symbols in Flash 279 Compiling and exporti...

Page 5: ...lip position and appearance 357 Dragging movie clips 359 Creating movie clips at runtime 360 Adding parameters to dynamically created movie clips 364 Managing movie clip depths 366 About caching and s...

Page 6: ...ructing a sample script 588 Chapter 15 Working with Images Sound and Video 591 About loading and working with external media 592 Loading external SWF and image files 593 About loading and using extern...

Page 7: ...Code Values 781 Appendix D Writing Scripts for Earlier Versions of Flash Player 787 About targeting earlier versions of Flash Player 787 Using Flash 8 to create content for Flash Player 4 788 Appendi...

Page 8: ...8 Contents...

Page 9: ...xperience you ll probably want to use ActionScript For more information see the following topics Intended audience 9 Updating Flash XML files 10 System requirements 10 About the documentation 10 Addit...

Page 10: ...h Player 7 7 0 19 0 contained a new method for the System object System security loadPolicyFile To access this method you must use the Player Updater installer to update all the Flash players that are...

Page 11: ...s how to create custom classes and objects in ActionScript This chapter also lists the built in classes in ActionScript and provides a brief overview of how you use them to access powerful features in...

Page 12: ...and writing ActionScript This chapter also lists standardized coding conventions such as naming variables and other conventions Appendix A Error Messages lists the error messages that the Flash compil...

Page 13: ...gy on page 803 Copy and paste code When you paste ActionScript from the Help panel into your FLA or ActionScript file you have to be careful about special characters Special characters include special...

Page 14: ...k the Clear button to see each manual that s available for more information see Where to find documentation on other subjects on page 17 For more information about other available resources see the fo...

Page 15: ...f additional sample files www macromedia com go flash_samples Where to find PDF files or printed documentation If you prefer to read documentation in printed format the PDF versions of each Help manua...

Page 16: ...oftware or you would like to request an enhancement to Flash please fill out the wishform at www macromedia com go wish If you report your bug or enhancement request on LiveDocs it will not be officia...

Page 17: ...romedia com community regularly hosts Macrochats a series of live presentations on a variety of topics by Macromedia employees or community members Check the website often for updates and to register...

Page 18: ...18 Introduction...

Page 19: ...eloped since its introduction several years ago With each new release of Flash additional keywords objects methods and other language elements were added to ActionScript There are also ActionScript re...

Page 20: ...ressive JPEG images and non animated GIF and PNG files If you load an animated file the first frame of the animation appears You can assign linkage identifiers to bitmap and sound files stored in the...

Page 21: ...de to apply many filters to objects on the Stage such as movie clip instances For information on filters and ActionScript see Working with filters using ActionScript on page 505 You can use the FileRe...

Page 22: ...r class in the flash filters package lets you apply matrix convolution filter effects The DisplacementMapFilter class in the flash filters package lets you use pixel values from a BitmapData object to...

Page 23: ...for the debugger player to outline the regions of the screen that are being redrawn that is dirty regions that are being updated The function has the player show what was redrawn but does not let you...

Page 24: ...of the MovieClip class which is an indexed array that contains each filter object that s currently associated with the instance The getRect method of the MovieClip class which returns properties that...

Page 25: ...stance The filters property in the TextField class which is an indexed array that contains each filter object that s currently associated with the TextField instance The gridFitType property in the Te...

Page 26: ...instance The _xmouse property in the Video class which lets you set the x coordinate of the mouse pointer position The _xscale property in the Video class which lets you set the horizontal scale perc...

Page 27: ...st and easier to use than earlier versions of the tool The changes are summarized in this section View hidden characters You can now use the Options pop up menu in the Script pane Debugger panel and O...

Page 28: ...SWF files and load data from any remote or local computer without configuring security settings In Flash Player 8 a SWF file cannot make connections to the local file system and the network such as t...

Page 29: ...twork only such as the Internet and not the local file system where the SWF file is installed Access to both the local file system and the network The local SWF file can read from the local file syste...

Page 30: ...30 What s New in Flash 8 ActionScript...

Page 31: ...ript pane and supporting tools to make writing scripts easier These tools include the Actions toolbox which gives you quick access to the core ActionScript language elements the Script navigator which...

Page 32: ...u write an event handler to respond to the event with an action Understanding when and where events occur will help you to determine how and where you will respond to the event with an action and whic...

Page 33: ...reached during playback A script attached to a frame is called a frame script One of the most common uses of frame scripts is to stop the playback when a certain keyframe is reached This is done with...

Page 34: ...l AS file you create a script within the FLA file and then use the include statement to access the code you ve stored externally as shown in the following example include core Functions as You can als...

Page 35: ...ions panel To create external scripts that you include or import into your application you can use the Script window File New and then select ActionScript File or your preferred text editor When you u...

Page 36: ...elements to your scripts by using the Add button on the Actions panel toolbar For more information see About the Actions panel and Script window toolbars on page 39 Script navigator The Script navigat...

Page 37: ...e 52 Using Escape shortcut keys on page 52 Showing hidden characters on page 53 Using the Find tool on page 54 Checking syntax and punctuation on page 55 Importing and exporting scripts on page 56 Abo...

Page 38: ...es in the Script window see the following topics About the Actions panel and Script window toolbars on page 39 About ActionScript editing options on page 41 About code hinting in Flash on page 44 Form...

Page 39: ...55 Importing and exporting scripts on page 56 For features specific only to the Actions panel such as script pinning and the Script navigator see About Actions panel features on page 58 About the Acti...

Page 40: ...For more information see Formatting code on page 50 Show Code Hint If you ve turned off automatic code hinting you can use Show Code Hint to manually display a code hint for the line of code you re w...

Page 41: ...se options are available in the Script window see About the Script window on page 37 The options that are available in the Script window and Actions panel are discussed in About the Actions panel and...

Page 42: ...references Actions panel only Displays the ActionScript preferences dialog box For more information see About ActionScript preferences on page 42 Word wrap To wrap the lines of your script that exceed...

Page 43: ...tion is turned on the text you type after an opening parenthesis or opening curly brace is automatically indented according to the Tab Size setting in ActionScript preferences For more information see...

Page 44: ...rnal script files this feature helps you avoid overwriting a script that a team member has modified since you opened the application or publishing the application with older versions of scripts The wa...

Page 45: ...e hints Code hints are enabled by default By setting preferences you can disable code hints or determine how quickly they appear When code hints are disabled in preferences you can still display a cod...

Page 46: ...atements such as the for loop separate the parameters with semicolons Overloaded commands functions or methods that can be invoked with different sets of parameters such as gotoAndPlay or for display...

Page 47: ...already typed an opening parens Press Escape To manually display a code hint 1 Click in a code location where code hints can appear such as in the following locations After the dot following a stateme...

Page 48: ...5 About using suffixes to trigger code hints If you use ActionScript 1 or you want to display code hints for objects you create without strictly typing them see About typing objects to trigger code hi...

Page 49: ...ts on page 45 Object type Variable suffix Array _array Button _btn Camera _cam Color _color ContextMenu _cm ContextMenuItem _cmi Date _date Error _err LoadVars _lv LocalConnection _lc Microphone _mic...

Page 50: ...code more understandable For more information on using code hints see Using code hints on page 45 Formatting code You can specify settings to determine if your code is formatted and indented automati...

Page 51: ...rences In your scripts you can indent a line by selecting the line and pressing Tab To remove the indent select the line and press Shift Tab Using syntax highlighting In ActionScript as in any languag...

Page 52: ...to wrap long lines of code Typically you should enable line numbers and word wrap to make editing code much easier Line numbers make code easier to scroll and parse when you re editing or modifying t...

Page 53: ...which commands have Escape shortcut keys you can show them next to elements in the ActionScript toolbox To show or hide Escape shortcut keys From the Actions panel pop up menu select or deselect Esc...

Page 54: ...pane looks like this Using the Find tool The Find tool allows you to find and optionally replace text string in your scripts You may replace the first or all occurrences of the text in your script You...

Page 55: ...r you can do a quick check of your ActionScript code without leaving the FLA file Syntax errors are listed in the Output panel You can also check to see if a set of parentheses curly braces or bracket...

Page 56: ...t the first line of the external script to be located and then do either of the following In the Actions panel select Import Script from the pop up menu or press Control Shift I Windows or Command Shi...

Page 57: ...g message when you export ActionScript files you can change the export encoding preference or turn this warning off in ActionScript preferences To select text encoding options for importing or exporti...

Page 58: ...indow and the Actions panel see the sections in About coding in the Actions panel and Script window on page 38 For features only available in the Actions panel see these sections About Script Assist o...

Page 59: ...current location on the timeline is on Frame 1 of the layer named Cleanup The tab at the far left always follows your location along the timeline That script is also pinned it is shown as the right m...

Page 60: ...and select Close Script or Close All Scripts Select Close Script or Close All Scripts from the pop up menu at the upper right of the Actions panel With the mouse pointer focused in the Script pane pre...

Page 61: ...an attach to objects in your Flash document without having to create the ActionScript code yourself Behaviors provide you with prewritten ActionScript functionality such as frame navigation loading of...

Page 62: ...the Flash document s publish settings to change the version of ActionScript that will be used when the document is published You can also set the classpath for the current document by passing the glo...

Page 63: ...to the ActionScript version pop up menu to modify the document level classpath For more information see Modifying the classpath on page 63 Modifying the classpath When you use ActionScript 2 0 you ca...

Page 64: ...the ActionScript Version pop up menu 4 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...

Page 65: ...formation on ASO files see Using ASO files on page 282 For more information on the organization of this directory see the readme file in the Classes folder Include classes folder Contain all of the gl...

Page 66: ...66 Writing and Editing ActionScript 2 0...

Page 67: ...ssages on page 773 Key facts about ActionScript 2 0 include the following points Scripts that use ActionScript 2 0 to define classes or interfaces must be stored as external script files with a single...

Page 68: ...ript 2 0 you can create custom classes and extend Flash s built in classes Strict data typing ActionScript 2 0 also lets you explicitly specify data types for variables function parameters and functio...

Page 69: ...ing ActionScript 2 0 with its strict data typing and its new methods and properties ActionScript 2 0 also offers a syntax that follows standards in other programming languages This makes the language...

Page 70: ...d 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 Data type annotations str...

Page 71: ...a types see the following sections About data 71 About data types 72 About variables 86 Organizing data in objects 108 About casting 110 About data Data refers to the numbers strings and other informa...

Page 72: ...e table in About primitive and complex data types on page 73 for more information ActionScript also has core classes such as Array and Date that are considered complex or reference data types For more...

Page 73: ...ue that is not a primitive value and that references the primitive values Often these are called reference data types Complex values belong to the Object data type or a data type that is based on the...

Page 74: ...a type can store values from Number MAX_VALUE very high to Number MIN_VALUE very low For more information see ActionScript 2 0 Language Reference and Number data type on page 78 Object Complex The Obj...

Page 75: ...users enter values into two TextInput component instances Two Boolean variables are created userNameEntered and isPasswordCorrect and if both variables evaluate to true a welcome message is assigned t...

Page 76: ...the Stage my_mc startDrag true parent_mc getURL http www macromedia com support product The second example returns the width of a movie clip called my_mc on the Stage The targeted instance must be a m...

Page 77: ...ctionScript 2 0 Language Reference null data type The null data type has only one value null This value means no value that is a lack of data You can assign the null value in a variety of situations t...

Page 78: ...ces a random integer between 10 and 17 inclusive var bottles Number 0 bottles 10 Math floor Math random 7 trace There are bottles bottles The following example finds the percent of the intro_mc movie...

Page 79: ...objects to organize information It creates a new object called user and creates three properties name age and phone which are String and Numeric data types var user Object new Object user name Irving...

Page 80: ...lue undefined and is automatically assigned to a variable to which a value hasn t been assigned either by your code or user interaction The value undefined is automatically assigned unlike null you do...

Page 81: ...Number data type var x 3 Because x was not declared using strict data typing the compiler cannot determine the type to the compiler the variable x can have a value of any type See Assigning a data typ...

Page 82: ...pplication 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...

Page 83: ...of type Student var myStudent Student new Student For this example suppose you type the following code in the Student as class file class Student public var status Boolean property of Student objects...

Page 84: ...if you implement strict data typing in your code make sure you set your publish settings to ActionScript 2 0 You can specify the publish settings and define which version of ActionScript you want to...

Page 85: ...nd methods that are not known at compile time Because the code is less restrictive it can lead to benefits in some coding situations For example the following code creates a function named runtimeTest...

Page 86: ...ses see Chapter 7 Classes on page 225 About variables A variable is a container that holds information The following ActionScript shows what a variable looks like in ActionScript var myVariable Number...

Page 87: ...ing a value independent of variables in other SWF files or movie clips To view the value of a variable use the trace statement to send the value to the Output panel Then the value displays in the Outp...

Page 88: ...do not set its value that variable is uninitialized The value of an uninitialized variable defaults to the value undefined For more information on creating and using variables see About variables on...

Page 89: ...utput panel when you test the SWF file Type mismatch in assignment statement found Number where String is required This error tells you that you attempted to set the wrong data type to a specified var...

Page 90: ...this example using the shorthand method can save a lot of typing and time especially when you define instances of objects It is important to be familiar with this alternate syntax because you will enc...

Page 91: ...age 130 A variable must be unique within its scope see About variables and scope on page 96 A variable should not be any element in the ActionScript language such as a class name If you don t follow t...

Page 92: ...nd operators that represent a value For example in the expression i 2 i and 2 are operands and is an operator If you do not initialize a variable before you use it in an expression the variable is und...

Page 93: ...d click the second button you added to the Stage This button properly opens the web page The type of data that a variable contains affects how and when the variable s value changes Primitive data type...

Page 94: ...Output panel The Object data type can contain such a large amount of complex information that a variable with this type doesn t hold an actual value it holds a reference to a value This reference is...

Page 95: ...ence to it The trace statement sends tom jack to the Output panel In the following example myArray contains an Array object so you pass the array to function zeroArray by reference The function zeroAr...

Page 96: ...icates not only when and where you can refer to variables but also for how long a particular variable exists in an application When you define variables in the body of a function they cease to exist a...

Page 97: ...s global variable and displays 100 This example simply shows that the global variable is not accessed in the scope of the count function However you could access the global scoped variable if you pref...

Page 98: ...ng action add stop after the trace statement You must declare a timeline variable before trying to access it in a script For example if you put the code var myNum Number 15 in Frame 20 any scripts att...

Page 99: ...Timeline In the next example you can see how certain variables live only for the life of a specific function and can generate errors if you try to refer to the variable outside the scope of that func...

Page 100: ...od practice to use local variables in the body of a function so the function can act as an independent piece of code You can change a local variable only within its own block of code If an expression...

Page 101: ...As and save the document on your desktop 3 Select Frame 1 of the Timeline and add the following code in the Actions panel this createTextField myTxt 100 0 0 100 20 myTxt autoSize left myTxt text _leve...

Page 102: ...ML 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 object classid clsid d27cdb...

Page 103: ...Ben note space at end of value Jerry note space at beginning of variable name and an empty value flavor Half Baked To avoid this you need to escape the ampersand character in the name value pair with...

Page 104: ...ished files where you saved myflashvars fla on your hard drive and open the HTML document myflashvars html by default in an HTML editor such as Dreamweaver or Notepad 6 Add the code that appears in bo...

Page 105: ...urces such as text files XML documents and so on You can find much more information on loading variables including name value pairs in Chapter 16 Working with External Data on page 633 In Flash you ca...

Page 106: ...for the instance of the Loader class and a couple of functions that are called depending on whether the file is successfully loaded or not To use variables in a project 1 Create a new Flash document a...

Page 107: ...ovie clip to load the image into 3 Select Control Test Movie to test the document Because you re testing the Flash document in the authoring tool no value for imgUrl will be passed by FlashVars or alo...

Page 108: ...ActionScript For example the built in Date class provides information from the system clock on the user s computer You can use the built in LoadVars class to load variables into your SWF file You can...

Page 109: ...Var 28 thirdVar Tue Jan 1 00 00 00 GMT 0800 1980 You can also use arrays to create objects Instead of having a series of variables such as firstname1 firstname2 and firstname3 to represent a collectio...

Page 110: ...on page 158 For more information on objects see Chapter 7 Classes on page 225 About casting ActionScript 2 0 lets you cast one data type to another Casting an object to a different type means you con...

Page 111: ...erted to the compiler that foo is a Dog object and therefore the compiler assumes that foo bark is a legal statement However the compiler doesn t know that the cast will fail that is that you tried to...

Page 112: ...rforming the addition that yields the proper result Data conversion is important when working with data loaded using XML or FlashVars as shown in the following example var firstNum String 17 var secon...

Page 113: ...can form statements in ActionScript using syntax It contains many short code snippets and some examples to demonstrate fundamental language concepts Upcoming chapters contain longer and increasingly...

Page 114: ...language that you program with The compiler cannot understand incorrect syntax so you see errors or warnings displayed in the Output panel when you try to test the document in the test environment Th...

Page 115: ...d and debug if you encounter problems For more information about formatting ActionScript see Formatting ActionScript syntax on page 764 You can also see proper formatting of ActionScript in these sect...

Page 116: ...ject 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...

Page 117: ...or the case that variables are in when they are returned to the SWF file from the server For example if you use a ColdFusion web service property names from a structure or object might be all uppercas...

Page 118: ...n to a movie clip or to get or set the value of a variable or property For more information on assigning an instance name and using dot syntax to target an instance see the following topics About usin...

Page 119: ...re information on working with scope see About scope and targeting on page 123 and About variables and scope on page 96 Targeting an instance If you want something to work in your SWF file you need to...

Page 120: ...exercise in Targeting an instance on page 119 You can also target that nested instance using ActionScript Before you proceed with the following exercise you need to complete the exercise in Targeting...

Page 121: ...he specified class in this case MovieClip can add and access dynamic properties at runtime For more information about the dynamic statement see dynamic statement in the ActionScript 2 0 Language Refer...

Page 122: ...isibility to false Load the SWF onto level 99 loadMovieNum contents swf 99 Set the visibility of level 99 to false loaderClip onEnterFrame function _level99 _visible false Setting variables using a pa...

Page 123: ...u want to target the main timeline target the parent of the movie clip which is the main Stage Double click a movie clip and place the following ActionScript on the movie clip s timeline trace me this...

Page 124: ...onScript 1 0 in Flash Player 7 and earlier but it s not supported in ActionScript 2 0 and Flash Player 7 or Flash Player 8 Using slash syntax is not recommended unless you do not have another option s...

Page 125: ...appended to the end of your statements by default Another place you use semicolons is in for loops You use the semicolon to separate parameters as shown in the following example The example loops from...

Page 126: ...you avoid errors in your ActionScript when you forget to add braces to your code The following example shows code that is written using poor form var numUsers Number if numUsers 0 trace no users foun...

Page 127: ...splays a simple class file that could be used to create a Student object You learn more about class files in Chapter 7 Classes on page 225 To use curly braces in an ActionScript file 1 Select File New...

Page 128: ...ave As and name the new file checkform fla 3 Drag an instance of the Label component from the Components panel onto the Stage 4 Open the Property inspector Window Properties Properties and with the La...

Page 129: ...Name H lastName Doe You can also use empty curly braces as a syntax shortcut for the new Object function For example the following code creates an empty Object instance var myObject Object Parentheses...

Page 130: ...re constant unchanging values within your Flash documents Examples of a literal include true false 0 1 52 or even the string foo The following examples are all literals 17 hello 3 9 4 null undefined t...

Page 131: ...tring object secondStr var firstStr String foo var secondStr String new String foo Use string literals unless you specifically need to use a String object for better performance For more information o...

Page 132: ...a sign that the ActionScript is inelegant and not intuitive When you enable syntax coloring comments are gray by default Comments can be any length without affecting the size of the exported file and...

Page 133: ...ons are clicked By placing large chunks of script in a comment block called commenting out a portion of your script you can test specific parts of a script For example when the following script runs n...

Page 134: ...modify their placement after using the Auto Format button Comments inside classes You use comments in your classes and interfaces to document them to help developers understand the contents of your cl...

Page 135: ...cannot be altered so they are values that don t change throughout an application Flash includes several predefined constants which can help simplify application development An example of constants ca...

Page 136: ...ActionScript to work it may be necessary to disable keyboard shortcuts in the authoring environment Select Control Test Movie from the main menu then while previewing the SWF file in the player selec...

Page 137: ...and save it as const fla 5 Open the Actions panel and type the following code on Frame 1 of the Timeline trace ConstExample EXAMPLE_STATIC output Global access When you declare the EXAMPLE_STATIC pro...

Page 138: ...ses see Chapter 7 Classes on page 225 About keywords Keywords are words in ActionScript that do one specific thing For example you use the var keyword to declare a variable The var keyword is shown in...

Page 139: ...rds in Flash that cause errors in your scripts The following table lists keywords that are reserved for future use by ActionScript or the ECMAScript ECMA 262 edition 4 draft language specification You...

Page 140: ...ellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMenu ContextMenuItem CustomActions CustomFormatter CustomValidator DataGrid DataHolder DataProvider DataSet DataType Date DateChoo...

Page 141: ...write ActionScript You might differ from someone else who writes ActionScript in the way you form syntax such as the way you space out your statements or where you put curly braces in your code Even...

Page 142: ...onScript code The opening brace is placed at the end of the compound statement The closing brace begins a line and aligns with the beginning of the compound statement For more information on using bra...

Page 143: ...pecifies alternative tests to perform if previous conditions are false if passwordTxt text length 0 emailTxt text length 0 gotoAndStop invalidLogin else if passwordTxt text userID gotoAndPlay startPro...

Page 144: ...se the if statement to test whether an instance on the Stage is still within the boundaries of the Stage For example if a ball moves downward along the y axis you might need to detect when the ball co...

Page 145: ...login is valid you can redirect the user to a welcome page using the if block However if the login was invalid you can redirect the user to the login form and display an error message using the else b...

Page 146: ...ning or night time Then you can display an appropriate graphic The following code not only tests whether the value of x exceeds 20 but also tests whether the value of x is negative if x 20 trace x is...

Page 147: ...doesn t contain a break statement a condition called fall through occurs In this situation the following case statement also executes until a break statement is encountered or the switch statement end...

Page 148: ...e default case here trace you pressed some other key Key addListener listenerObj 3 Select Control Test Movie to test the ActionScript Type letters using the keyboard including the a e or i key When yo...

Page 149: ...e try block completes normally the code in the finally block still executes You write try catch and try catch finally statements using the following format try catch try statements catch myError state...

Page 150: ...zero 5 Return to the authoring environment and change the following line of code var n2 Number 0 to var n2 Number 2 6 Select Control Enter to test the document again If the value of n2 equals zero an...

Page 151: ...w DivideByZeroException else if n2 0 throw new Error n2 cannot be less than zero else trace n1 n2 catch err DivideByZeroException trace err toString catch err Error trace An unknown error occurred err...

Page 152: ...arrot Using a conditional expression you would write the same code using this format var numOne Number 8 var numTwo Number 0 trace numTwo 0 numOne numTwo carrot As you can see the shortened syntax red...

Page 153: ...nts when a particular condition is true There are four types of loops in ActionScript for loops for in loops while loops and do while loops Each type of loop behaves somewhat differently and each one...

Page 154: ...a certain condition is true ActionScript can repeat an action a specified number of times or while a specific condition exists Use the while do while for and for in actions to create loops This sectio...

Page 155: ...page 157 To loop through the children of a movie clip or an object Use the for in statement Children include other movie clips functions objects and variables The following example uses the trace stat...

Page 156: ...lash document The following code is an example of an infinite loop BAD CODE creates an infinite loop USE AT OWN RISK var i Number for i 0 i 10 i trace i The value of i is initialized to 0 and the end...

Page 157: ...n update statements You must supply three expressions to a for statement a variable that is set to an initial value a conditional statement that determines when the looping ends and an expression that...

Page 158: ...the ActionScript 2 0 Language Reference Using for in loops Use the for in statement to loop through or iterate through the children of a movie clip properties of an object or elements of an array Chi...

Page 159: ...27 myObj city San Francisco If you write a for in loop in a class file an external ActionScript file instance members are not available within the loop but static members are However if you write a fo...

Page 160: ...k of code For example the following code traces numbers to the Output panel var i Number 0 while i 5 trace i i You see the following numbers traced to the Output panel 0 1 2 3 4 One disadvantage of us...

Page 161: ...ops You can use the do while statement to create the same kind of loop as a while loop However the expression is evaluated at the bottom of the code block in a do while loop it s checked after the cod...

Page 162: ...and name the document loops fla 3 Add the following code to Frame 1 of the Timeline var myArr Array new Array myArr 0 name One value 1 myArr 1 name Two value 2 var i Number var item String for i 0 i m...

Page 163: ...5 As such you can store different kinds of data in a single array including other arrays Each floor of this building can contain multiple kinds of content executives and accounting might share floor 3...

Page 164: ...t For example if you build an audio application in Flash you might have a user s playlist stored as an array of song information stored in objects Each object contains the song name artist name song d...

Page 165: ...your code The following text is displayed in the Output panel key 0 value value0 key 1 value value1 For more information on for in loops see Using for in loops on page 158 For information on how to c...

Page 166: ...be lost When you copy the value from one of the array indexes into a temporary variable you can save the value and safely copy it back later in your code For example if you use the following code inst...

Page 167: ...are displayed again In the following ActionScript if you create an element at array index 5 in an array the length of the array returns 6 because the array is zero based and not the actual number of i...

Page 168: ...ace monthArr Jan Feb Mar Apr May JUN Jul Aug Sep Oct Nov Dec Even though you deleted the item at array index 5 the array length is still 12 and the item at array index 5 changed to a blank string inst...

Page 169: ...ar in the Output panel Creating multidimensional arrays In ActionScript you can implement arrays as nested arrays that are essentially arrays of arrays Nested arrays also known as multidimensional arr...

Page 170: ...shown below trace twoDArray 5 Add the following ActionScript at the end of your code on Frame 1 of the Timeline trace twoDArray 0 0 one trace twoDArray 1 1 four To retrieve elements of a multidimensi...

Page 171: ...of the Timeline from previous example var gridSize Number 3 var mainArr Array new Array gridSize var i Number var j Number for i 0 i gridSize i mainArr i new Array gridSize for j 0 j gridSize j mainA...

Page 172: ...is what you will probably use associative arrays for most often The association between a key and value is commonly referred to as its binding the key and value are mapped to each other For example a...

Page 173: ...o create associative arrays in ActionScript 2 0 Use an Object constructor Use an Array constructor Both of these ways are demonstrated in upcoming examples If you use the Object constructor to create...

Page 174: ...million trace monitorInfo aspectRatio monitorInfo colors After you use using either an object literal or the Object class constructor to create the array you can add new values to the array using eit...

Page 175: ...rInfo using the Array constructor and adds a key called type and a key called resolution along with their values 3 Select Control Test Movie The Output panel displays the following text Flat Panel 160...

Page 176: ...are operands and is an operator You use expressions and operators frequently throughout your code You can combine operators and values to create an expression or you can call a function The parts of...

Page 177: ...not fall into these categories see the ActionScript 2 0 Language Reference which contains information about all the operators you can use The following sections show you some common uses for operators...

Page 178: ...ether In the first code example it adds the current value of myScore and the number 1 and then stores the result into the variable myScore The second code example uses the addition assignment operator...

Page 179: ...tors are processed ActionScript has a hierarchy that determines which operators execute before others There is a table that outlines this hierarchy at the end of this section Although it may seem natu...

Page 180: ...on on assignment operators see Using assignment operators on page 194 For more information on the conditional operator see About the conditional operator on page 199 For example consider the less than...

Page 181: ...l Left to right x Pre increment Right to left x Pre decrement Right to left Unary negation such as x 1 Left to right Bitwise NOT Right to left Logical NOT Right to left new Allocate object Right to le...

Page 182: ...compare strings to determine which is first alphabetically Strings with uppercase characters precede strings that are lowercase That means that Egg comes before chicken var c String chicken var e Stri...

Page 183: ...e strings when you write trace statements For example you might write the following var myNum Number 10 trace The variable is myNum When you test this code the Output panel displays the following The...

Page 184: ...strated in the following ActionScript var someUser Object name Hal id 2001 trace User s name is someUser name User s name is Hal trace User s id is someUser id User s id is 2001 For example the follow...

Page 185: ...ip1 nestedClip2 nestedClip3 nestedClip4 11 Add the following code to Frame 1 of the main Timeline var i Number for i 1 i 4 i myClip nestedClip i _visible false This ActionScript toggles the visibility...

Page 186: ...xNum 0 trace xNum 1 When you trace this code the text in the Output panel reads 0 1 The operators in this table have equal precedence About unary operators Unary operators take one operand The increm...

Page 187: ...erators on page 188 About additive operators The additive operators take two operands and perform addition or subtraction calculations Other numeric operators include multiplicative operators For info...

Page 188: ...est Movie to test the ActionScript The Example one code block traces but the Example two code block does not The first example uses a preincrement firstScore to increment and calculate firstScore befo...

Page 189: ...ity operators The equality operators take two operands compare their values and return a Boolean value All of the operators in this table have equal precedence For information on using equality operat...

Page 190: ...h and display a message in the Output panel if there are no items in the array var myArr Array new Array if myArr length 0 trace the array is empty When you select Control Test Movie the string the ar...

Page 191: ...erands are different types the equality operator returns false The strict inequality operator returns the opposite of the strict equality operator The following ActionScript demonstrates the key diffe...

Page 192: ...mc lineTo 0 20 submit_mc lineTo 0 0 submit_mc endFill submit_mc _x 110 submit_mc onRelease function evt_obj Object Void var myNum Number Number myTxt text if isNaN myNum trace Please enter a number re...

Page 193: ...ence and associativity on page 179 About assignment operators The assignment operators take two operands and assign a value to one operand based on the value of the other operand All of the operators...

Page 194: ...you can have problems if you try to add values in an expression as you can see in the following example trace the sum of 5 2 is 5 2 the sum of 5 2 is 52 Flash concatenates the values 5 and 2 instead o...

Page 195: ...it_mc 30 submit_mc beginFill 0xFF0000 submit_mc moveTo 0 0 submit_mc lineTo 100 0 submit_mc lineTo 100 20 submit_mc lineTo 0 20 submit_mc lineTo 0 0 submit_mc endFill submit_mc _x 110 submit_mc onRele...

Page 196: ...Number myTxt text if isNaN myNum trace Please enter a number return if myNum 10 myNum 20 trace Your number is between 10 and 20 else trace Your number is NOT between 10 and 20 About bitwise shift ope...

Page 197: ...bitwise shift operators see About bitwise shift operators on page 196 For a list of bitwise logical operators see About bitwise logical operators on page 197 Using bitwise operators in Flash isn t ve...

Page 198: ...Array DESCENDING constants my_array sort 1 2 numbers my_array sort 3 adding the numbers Although it might not be immediately obvious the number values for the sort options are actually bitwise digits...

Page 199: ...mal places instead In the next example you also use the division and multiplication operators to calculate a user s score based on the number of correct answers divided by the total number of question...

Page 200: ...Math round and then divide by 100 you can make Flash round the number to 2 decimal places This results in a more accurate score 4 Try changing the correctAnswers variable to 3 and select Control Test...

Page 201: ...ds of functions that you can write in your Flash applications For information on what functions and methods are as well as exercises in which you write and use functions and methods in Flash see the f...

Page 202: ...output and purpose a person using the function does not need to understand exactly how it works internally The basic syntax for a simple named function is function traceMe trace your message traceMe F...

Page 203: ...uding built in functions named and user defined functions anonymous functions callback functions constructor functions and function literals The following sections contain information on how to define...

Page 204: ...the ones in the previous code sample see Chapter 7 Classes on page 225 The methods that you use in your code might belong to a class that is built into the ActionScript language MovieClip and Math ar...

Page 205: ...ions on page 208 About function literals on page 211 Targeting and calling user defined functions on page 213 About constructor functions on page 211 For information on writing and using functions and...

Page 206: ...ich can cause errors during runtime Top level functions are easy to use To call a function simply use the function name and pass any parameters required by that function For information on required pa...

Page 207: ...ameters are sometimes called arguments For more information on parameters see Passing parameters to a function on page 218 function block contains all of the ActionScript code that s carried out by th...

Page 208: ...itself you reference the anonymous function when you create it When you write ActionScript code you will create many anonymous functions Anonymous functions are commonly used when you work with event...

Page 209: ...nonymous function to handle the onLoad event For more information on callback functions see Chapter 10 Handling Events on page 329 You could also use anonymous functions with the setInterval function...

Page 210: ...function myWidth function myWidth trace foo the following does not work because you are calling an anonymous function myWidth var myWidth Function function trace foo For more information see Writing...

Page 211: ...you create an instance of a class by using the new keyword such as var my_xml XML new XML The constructor function has the same name as the class that contains it For example a custom Person class tha...

Page 212: ...ts that indicate what the function does The following example is a function named areaOfCircle with the parameter radius function areaOfCircle radius Number Number return Math PI radius radius trace a...

Page 213: ...as defined on the current timeline and requires no parameters this initialize The following example uses a relative path to call the list function which was defined in the functionsClip movie clip thi...

Page 214: ...pending on what data types are passed into them As with variables you cannot use special characters and the method name cannot start with a number For more information see Naming conventions on page 7...

Page 215: ...tement you have to call the helloWorld function 4 Type the following line of ActionScript code after the function helloWorld This code calls the helloWorld function 5 Select Control Test Movie to test...

Page 216: ...in the previous code sample you don t need to place functions on a timeline The following example also puts functions in a class file This is a good practice to adopt when you create large applicatio...

Page 217: ...en the Actions panel 6 Type the following ActionScript into the Script pane var randomMonth Number Utils randomRange 0 11 var min Number Utils arrayMin 3 3 5 34 2 1 1 3 var max Number Utils arrayMax 3...

Page 218: ...ameters see Passing parameters to a function on page 218 For more information on variables and data see Chapter 4 Data and Data Types on page 71 Passing parameters to a function Parameters also referr...

Page 219: ...ters For example the startDrag method of the MovieClip class takes five parameters lockCenter left top right and bottom startDrag lockCenter Boolean left Number top Number right Number bottom Number V...

Page 220: ...it as functionTest2 fla 2 Add the following code to Frame 1 of the main Timeline function addNumbers a Number b Number c Number Number return a b c trace addNumbers 1 4 6 11 trace addNumbers 1 4 NaN...

Page 221: ...s without returning a value The next example returns the processed value You are capturing that value in a variable and then you can use that variable within your application To return a value and cap...

Page 222: ...n you call the formatText function Understanding methods Methods are functions that are associated with a class The class could be a custom class or built in classes that are part of the ActionScript...

Page 223: ...ipt code defines a function called eatCabbage function eatCabbage trace tastes bad eatCabbage However if you write the eatCabbage function within a class file and for example call eatCabbage in the FL...

Page 224: ...methods and words with mixed cases for concatenated words making sure that the first letter is lowercase For example you might name methods in the following ways sing boogie singLoud danceFast You use...

Page 225: ...hapter shows you how to create your own custom classes and how to use them within your Flash documents You learn about the Flash classpath and how a class should be documented so that other people who...

Page 226: ...es all of the properties that distinguish a series of objects For example a User class represents a bunch of users who are using your application Then you have an instantiation of the class which for...

Page 227: ...r even extend the top level classes and add your own functionality or modify existing functionality For example About class members on page 250 in this chapter shows you how to make a custom Person cl...

Page 228: ...ize your ActionScript class files in packages A package is a directory that contains one or more class files and that resides in a designated classpath directory see About importing class files on pag...

Page 229: ...ine a new type of object in your application A class describes the properties data and behaviors methods for an object much like an architectural blueprint describes the characteristics of a building...

Page 230: ...tement lets you access the BlurFilter using only the class name instead of always having to use the fully qualified name This can save typing and reduce the chance of making typing mistakes with impor...

Page 231: ...describe the kind of information a variable or ActionScript element can contain such as Boolean Number and String For more information see About data types on page 72 Expressions have values while va...

Page 232: ...ch individual cat is said to be an instance of the Cat class Likewise in OOP a class defines a blueprint for a type of object The characteristics and behaviors that belong to a class are jointly refer...

Page 233: ...f methods Using the cat analogy an interface is similar to a blueprint of a cat the blueprint tells you which parts you need but not necessarily how those parts are assembled or how the parts work You...

Page 234: ...s long as the programming interface doesn t change For more information on encapsulation see About using encapsulation on page 261 Polymorphism OOP lets you express differences between individual clas...

Page 235: ...include a general description of the code as well as author and version information Add your import statements if applicable Write a package statement class declaration or interface declaration as fo...

Page 236: ...private var __password String constructor statement public function User p_username String p_password String this __username p_username this __password p_password public function get username String r...

Page 237: ...ce After trace t username user1 username 1nu trace t password user1 password 1wp Because the User class you created previously is very basic the ActionScript in the Flash document is also very straigh...

Page 238: ...es involves the following steps 1 Define a class in an external ActionScript class file For information on defining and writing a class file see Writing custom class files on page 235 2 Save the class...

Page 239: ...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...

Page 240: ...the subdirectory that contains the file An include statement in a FLA file can only bring in code that is valid inside FLA files and the same goes for other places that include statements can live For...

Page 241: ...h tab and then click the Settings button Using a global classpath The global classpath is a classpath that s shared by all of your Flash documents You can modify the global classpath using the Prefere...

Page 242: ...es only to FLA files You set the document level classpath in the Publish Settings dialog box for a particular FLA file File Publish Settings then click the Flash tab and then click ActionScript 2 0 Se...

Page 243: ...er manually type a file path or you can click the Browse to Path button to browse to the directory you want to add to the classpath For more information on packages see About packages on page 228 How...

Page 244: ...ht side For example in the following statement firstUser is the instance and username is the property firstUser username You can also use the top level or built in classes that make up the ActionScrip...

Page 245: ...e functions that you associate with a class For more information on functions and methods see Chapter 6 Functions and Methods on page 201 The following example shows you how you would create a method...

Page 246: ...as a container for an image and its URL class Picture private var __infoObj Object public function Picture src String this __infoObj new Object this __infoObj src src public function showInfo Void tra...

Page 247: ...Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript XML_Menu About public private and static methods and properties members When you write Acti...

Page 248: ...his ID 15 trace this ID 15 trace myMethod If you want to add a public property you use the word public instead of private as you can see in the following sample code class Sample private var ID Number...

Page 249: ...instance of the class as shown in the following code trace Math PI 8 0 392699081698724 If you type this single line of code in the script pane of the Actions panel you see a result trace in the Output...

Page 250: ...ity 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 S...

Page 251: ...For every Person object the species is Homo sapiens It would be wasteful to store a unique copy of the string Homo sapiens for every instance of the class so this member should be a class member Class...

Page 252: ...tructuring your code Typically you might structure a design pattern as a solution for a common programming problem There are many established design patterns such as Singleton The Singleton design pat...

Page 253: ...n instance new Singleton return Singleton instance 3 Save the Singleton as document 4 Select File New and then select Flash Document to create a new FLA file and save it as singleton_test fla in the s...

Page 254: ...e is created In the following example you ll create a class called Widget that defines a single static instance counter named widgetCount Each time a new instance of the class is created the value of...

Page 255: ...ning that they are generally a public interface to change private class members You use getter and setter methods to define a property You access getter and setter methods as properties outside the cl...

Page 256: ...bles in your class read only Using getter and setter methods The syntax for getter and setter methods is as follows A getter method does not take any parameters and always returns a value A setter met...

Page 257: ...RickyM calling setUserName method user setUserName EnriqueI trace user getUserName EnriqueI 6 Select Control Test Movie to test the file Flash displays the following information in the Output panel R...

Page 258: ...in the same scope Getter and setter methods cannot have the same names as other properties For example in the previous example code you defined getter and setter methods named userName in this case yo...

Page 259: ...page 259 Creating dynamic classes By default the properties and methods of a class are fixed That is an instance of a class can t create or access properties or methods that weren t originally declar...

Page 260: ...inition The dynamic class modifier lets you do just that To create a dynamic class 1 Select File New and then select ActionScript File and then click OK 2 Select File Save As and name the file Person2...

Page 261: ...your subclasses dynamic or not class A extends MovieClip A is not dynamic dynamic class B extends A B is dynamic class C extends B C is dynamic class D extends A D is not dynamic dynamic class E exten...

Page 262: ...function set userName value String Void this __userName value public function get age Number return this __age public function set age value Number Void this __age value About using the this keyword i...

Page 263: ...xample In its most basic form a class declaration consists of the class keyword followed by the class name Person in this case and then left and right curly braces Everything between the braces is cal...

Page 264: ...You practice these guidelines in upcoming examples In general place only one declaration per line and do not place either the same or different types of declarations on a single line Format your decl...

Page 265: ...nly to those variables through a small group of getter and setter functions About naming class files Class names must be identifiers that is the first character must be a letter underscore _ or dollar...

Page 266: ...tool or by using an external editor Several external editors such as Macromedia Dreamweaver and Macromedia Flex Builder can create AS files To create a class file and class declaration 1 Select File N...

Page 267: ...he file in which it is declared that is it must reflect the directory package in which it is stored For more information on classpaths see About setting and modifying the classpath on page 240 For exa...

Page 268: ...already learned how to write the class declaration in Creating and packaging your class files on page 266 In this part of the chapter you write what s called the class file s constructor function Cons...

Page 269: ...t you ll add a special function called a constructor function To add the constructor functions to your class files 1 Open the ClassA as class file in the Flash authoring tool 2 Modify the existing cla...

Page 270: ...o the previous code 4 Save both ActionScript files before you proceed You use the post colon syntax for example var username String and var age Number in the variable declarations This is an example o...

Page 271: ...onstructor function doSomething Void trace ClassA doSomething The block of code in boldface creates a new method in the class which traces a string to the Output panel 3 In ClassA as select Tools Chec...

Page 272: ...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 con...

Page 273: ...is userName user Private members properties and methods are accessible only to the class that defines those members and to subclasses of that original class Instances of the original class or instance...

Page 274: ...nts in your classes and interfaces is an important part of documenting them for other users For example you might want to distribute your class files into the Flash community or you might be working w...

Page 275: ...ublic function doSomething Void trace ClassA doSomething The code above added a comment to the top of the class file It s always a good idea to add comments to your ActionScript and Flash files so tha...

Page 276: ...m in the current directory 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 cla...

Page 277: ...import com macromedia docs learnAs2 util UserClass Later in the same script you could reference that class by its abbreviated name as shown in the following example var myUser UserClass new UserClass...

Page 278: ...ass so you can use any of the methods or properties of the Array class with any array instance Or you can create you own class such as UserSettings and then create an instance of the UserSettings clas...

Page 279: ...age 259 3 Save your changes to the FLA file before you proceed You should now have a basic understanding of how to create and use classes in your Flash documents Remember that you can also create inst...

Page 280: ...ck OK to apply your changes and close the dialog box 13 Save the Flash document and select Control Test Movie The Output panel displays the text from your Animal class s constructor function Compiling...

Page 281: ...ame on Frame 10 of the content layer and drag several components onto the Stage 8 Right click each component except the ProgressBar in the Library panel and select Linkage from the context menu to lau...

Page 282: ...file Flash needs to regenerate an ASO file only when the following scenarios occur The corresponding AS file has been modified ActionScript files that contain definitions imported or used by the corre...

Page 283: ...s definition in an exported SWF file cannot be larger than 32 767 bytes If the bytecode is larger than that limit a warning message appears You can t predict the size of the bytecode representation of...

Page 284: ...ML prodXml ignoreWhite true prodXml onLoad function success Boolean if success If the XML successfully loads and parses set the class s productsXml variable to the parsed XML document and call the ini...

Page 285: ...tatic variables and functions see About public private and static methods and properties members on page 247 and Using class members on page 254 Another benefit of static variables is that static vari...

Page 286: ...Data Types on page 71 and Chapter 5 Syntax and Language Fundamentals on page 113 ActionScript also provides several built in classes complex data types These classes provide a variety of scripting fe...

Page 287: ...asses are the Camera MovieClip and LoadVars classes Other classes are organized into packages such as flash display All of these classes are sometimes referred to as built in classes predefined classe...

Page 288: ...ECMAScript include Array Boolean Date Error Function Math Number Object String and System To find more information on each class see the following table N OT E The CustomActions and XMLUI classes are...

Page 289: ...o add custom menu items to a ContextMenu object by using the ContextMenuItem class See ContextMenu ContextMenuItem The ContextMenuItem class lets you create new menu items that appear in the Flash Pla...

Page 290: ...in a SWF file is an instance of the MovieClip class You use the methods and properties of this class to control movie clip objects See MovieClip MovieClipLoader This class lets you implement listener...

Page 291: ...anguage It also lets you show or hide the Flash Player Settings panel and modify SWF file security settings See System TextField The TextField class provides control over dynamic and input text fields...

Page 292: ...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 Flas...

Page 293: ...transformation you can produce a result with a new set of ARGB color and alpha values See ColorMatrixFilter flash filters ColorMatrixFilter ConvolutionFilter The ConvolutionFilter class lets you apply...

Page 294: ...ash geom ColorTransform Matrix Represents a transformation matrix that determines how to map points from one coordinate space to another See Matrix flash geom Matrix Point The Point object represents...

Page 295: ...s provides functionality for the advanced anti aliasing capability in Flash Player 8 See TextRenderer flash text TextRenderer Class Description Locale This class lets you control how multilanguage tex...

Page 296: ...ave static members The relationship between an instance and its class is similar to the relationship between a house and its architectural blueprints as discussed in About top level and built in class...

Page 297: ...llowing example loops over an object to display each of its properties To loop over the contents of an object 1 Create a new Flash document and save it as forin fla 2 Add the following ActionScript to...

Page 298: ...lass Therefore you don t create an instance of the class to use those properties and methods For example all the properties of the Math class are static The following code invokes the max method of th...

Page 299: ...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 so...

Page 300: ...yhead reaches Frame 3 and loads the data If you want to preload a file that uses classes such as version 2 component classes you must preload the components in the SWF file To accomplish this you must...

Page 301: ...08 About inheritance In Chapter 7 Classes you saw how you could create a class file to create your own custom data types Learning how to create custom class files shows you how to move code off the ti...

Page 302: ...an Employee class that defines the basic methods and properties of a typical employee within a company You could then create a new class called Contractor that extends the Employee class and inherits...

Page 303: ...mmal class that is create a subclass of the Mammal class as follows class Marsupial extends Mammal The subclass inherits all the properties and methods of the superclass including any properties or me...

Page 304: ...re than one class allowed class B extends A class C extends B You can also use interfaces to implement a limited form of multiple inheritance For more information on interfaces see Chapter 9 Interface...

Page 305: ...etCount property Because the SubWidget class is a subclass of the Widget class you can access the widgetCount property through the SubWidget class and the compiler rewrites the reference in the byteco...

Page 306: ...t it allows you not only to provide new functionality to an existing class but also to modify existing functionality For example consider the Widget class that you created in Example Extending the Wid...

Page 307: ...dgetTest fla in the same directory as the ActionScript documents 8 In subWidgetTest fla type the following ActionScript into Frame 1 of the main Timeline var sw1 SubWidget new SubWidget var sw2 SubWid...

Page 308: ...class Open the SubWidget class again and modify the SubWidget class s constructor to call the superclass s doSomething method add the code that s in boldface public function SubWidget trace Creating s...

Page 309: ...ocedure demonstrates this example in Flash To use polymorphism in an application 1 Create a new ActionScript document and save it as Mammal as This document is the base class for a few different anima...

Page 310: ...Mammal instance or any instance that extended the Mammal class 4 Create a new ActionScript file and save it as Cat as in the same directory as the Mammal as class file you created in step 1 5 In Cat...

Page 311: ...t class 9 Save your changes to the ActionScript document 10 Create another ActionScript document in the same directory as your other files and save it as Monkey as 11 In Monkey as type the following A...

Page 312: ...mal info in 4 columns of HTML text using tab stops info_txt htmlText textformat tabstops 110 200 300 info_txt htmlText b Mammal tGender tSleep tPlay b for i 0 i len i info_txt htmlText p mammals_arr i...

Page 313: ...re not familiar with building classes make sure that you read Chapter 7 Classes before you try the tutorials and examples in this chapter For more information on working with interfaces see the follow...

Page 314: ...of whom is working on a different class within the same application While designing the application you agree on a set of methods that the different classes use to communicate You create an interface...

Page 315: ...ions To use the interface keyword you must specify ActionScript 2 0 and Flash Player 6 or later in the Flash tab of your FLA file s Publish Settings dialog box The interface keyword is supported only...

Page 316: ...od declarations An interface can contain only method function declarations including parameters parameter types and function return types For more information on conventions for structuring classes an...

Page 317: ...d X from interface IMyInterface You see this error message because any class that extends an interface must define each method that s listed in the interface document 8 Modify the MyClass document aga...

Page 318: ...in packages are the same as those for classes see About naming class files on page 265 Creating interfaces as data types Like a class an interface defines a new data type You can consider any class t...

Page 319: ...ActionScript code creates an instance of the Box class which you declare as a variable of the Box type 9 Save your changes to the Flash document and then select Control Test Movie to test the SWF file...

Page 320: ...One consideration you need to make when extending interfaces is that you receive error messages in Flash if multiple interface files declare functions with the same names but have different parameter...

Page 321: ...ed a superclass and implemented multiple interfaces you would use code similar to the following class ClassA extends ClassB implements Ib Ic Id Example Using interfaces In this example you create a si...

Page 322: ...lowing code class FlashPaper implements IDocumentation private static var __version String 1 2 3 4 public function downloadUpdates Void public function checkForUpdates Boolean return true public funct...

Page 323: ...as and click the Check Syntax button and you should no longer receive any errors In the previous section you created a class based on the IDocumentation interface file In this section you create a new...

Page 324: ...Number return z 5 6 Save your changes to the ClassB as document and then create a new Flash document and save it as classbTest fla in the complexInterface directory This class file tests the ClassB cl...

Page 325: ...the following ActionScript code into the Script window filename InterfaceB as interface InterfaceB public function o Void 13 Save your changes to the InterfaceB as document and then create a new Actio...

Page 326: ...w method definition 19 In InterfaceC as type the following ActionScript code into the Script window filename InterfaceC as interface InterfaceC extends InterfaceA public function p Void 20 Save your c...

Page 327: ...e to test the SWF file The values 15 12 o and p display in the Output panel These values are the values that return from the ClassE k ClassE n ClassE o and ClassE p methods Since the ClassE class impl...

Page 328: ...328 Interfaces...

Page 329: ...work the contents of that file might appear in a text field You can handle events in ActionScript in several ways Using event handler methods on page 330 Using event listeners on page 332 Using button...

Page 330: ...e event handlers Button ContextMenu ContextMenuItem Key LoadVars LocalConnection Mouse MovieClip MovieClipLoader Selection SharedObject Sound Stage TextField XML and XMLSocket For more information abo...

Page 331: ...the following example that you assign the function reference not the function s return value to the onPress event handler Incorrect next_btn onPress goNextFrame Correct next_btn onPress goNextFrame Re...

Page 332: ...function that decreases the transparency of the movie clip FadeAlpha class sets transparency when you click the movie clip class FadeAlpha extends MovieClip function onPress this _alpha 10 For specif...

Page 333: ...le on page 334 The Stage class can broadcast events You can find a sample source file stagesize fla in the Samples folder on your hard disk This sample demonstrates how the Stage scaleMode property af...

Page 334: ...events you call the removeEventListener method of the broadcaster object passing it the name of the event to remove and the listener object broadcasterObject removeListener listenerObject Event listen...

Page 335: ...der property of the text field that has focus to true 6 To register the focusListener object to receive events from the Selection object add the following code to the Actions panel Registers focusList...

Page 336: ...e authoring tool Next you tell the my_ldr instance to listen for each of the two specified events progress and complete and specify the listener object or function to execute when the event is dispatc...

Page 337: ...nt handler broadcasts movie clip events and the on event handler handles button events To attach an event handler to a button or movie clip instance click the button or movie clip instance on the Stag...

Page 338: ...button in a SWF file the button can have an on press handler that tells the SWF file to play and the same button can have an onPress method for which you define a function that tells an object on the...

Page 339: ...lowing ActionScript directly on the movie clip symbol on the Stage on press trace on press 7 Add the following ActionScript to Frame 1 of the main Timeline box_mc onPress function trace box_mc onPress...

Page 340: ...trace You rolled over or rolled out You can also add key press events using on handlers For example the following code traces a string when you press the number 3 on the keyboard Select a button or m...

Page 341: ...ip instance To assign multiple handlers to an object 1 Create a new Flash document and name it assignMulti fla 2 Select Frame 1 of the Timeline and add the following code in the Actions panel this cre...

Page 342: ...e clip by adding the frame labels _up _over and _down to the movie clip s timeline When the user moves the mouse over the movie clip or clicks it the playhead is sent to the frame with the appropriate...

Page 343: ...sign a function to one of the movie clip object s mouse event handlers onPress onRelease and so forth as discussed in Using event handler methods on page 330 17 Select Control Test Movie to test the F...

Page 344: ...lips variables as well as function and method calls are invoked in the scope of the timeline that contains the button instance For instance the following on event handler produces different results th...

Page 345: ..._mc clip However the same code placed on the root timeline for a button instance would instead play the root timeline my_btn onPress function this play plays root timeline For more information about t...

Page 346: ...oadVarsDone function relies on the params_lv object by reference Therefore the onLoadVarsDone function is expecting a params_lv params_lv instance that does not exist To correctly invoke the onLoadVar...

Page 347: ...line that contains the button as shown in the following code Attached to button on main timeline on press trace this _level0 Using the Delegate class The Delegate class lets you run a function in a sp...

Page 348: ...entObj target instance trace t this this this createClassObject Button one_button 10 label One one_button move 10 10 one_button addEventListener click clickHandler this createClassObject Button two_bu...

Page 349: ...st Movie to test the Flash document 5 Click each button instance on the Stage to see which scope in which the event is handled a Click the first button on the Stage to trace the following text in the...

Page 350: ...350 Handling Events...

Page 351: ...instance name the instance name identifies it as an object of the MovieClip class type You use the properties and methods of the MovieClip class to control the appearance and behavior of movie clips a...

Page 352: ...ps Some methods of the MovieClip class perform the same tasks as functions of the same name other MovieClip methods such as hitTest and swapDepths don t have corresponding function names The following...

Page 353: ...r the function s target parameter to indicate the target of the function The following MovieClip methods can control movie clips or loaded levels and do not have equivalent functions MovieClip attachM...

Page 354: ...clip once and then execute a series of methods on that clip The with statement works on all ActionScript objects for example Array Color and Sound not only movie clips The with statement takes a movi...

Page 355: ...ded by the loadMovie method Explicitly unloading SWF files with unloadMovie ensures a smooth transition between SWF files and can decrease the memory that Flash Player requires It can be more efficien...

Page 356: ...ame In the following example the loaded SWF file contents swf also declares a variable named userName on its root timeline In contents swf _root userName Mary After contents swf loads into the movie c...

Page 357: ...When you load an image into a movie clip the upper left corner of the image is placed at the registration point of the movie clip Because this registration point is often the center of the movie clip...

Page 358: ...es are affected by transformations on the movie clip s parent and transform the movie clip and any of the clip s children The _focusrect _highquality _quality and _soundbuftime properties are global t...

Page 359: ...then trigger another action as shown in the following example Drag a piece of garbage garbage_mc onPress function this startDrag false When the garbage is dragged over the trashcan make it invisible...

Page 360: ...mples 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 Application...

Page 361: ...d the image into the container and place the event handler on the parent movie clip Creates a parent movie clip to hold the container this createEmptyMovieClip my_mc 0 Creates a child movie clip insid...

Page 362: ...and Tutorials Samples ActionScript Animation On the Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript Animation Attaching a movie clip symbol...

Page 363: ...the symbol to the Stage at runtime by using attachMovie To attach a movie clip to another movie clip 1 Assign a linkage identifier to a movie clip library symbol as described in the previous example...

Page 364: ...wing syntax with attachMovie myMovieClip attachMovie idName newName depth initObject Use the following syntax with duplicateMovie myMovieClip duplicateMovie idName newName depth initObject The initObj...

Page 365: ...sample photo gallery application on your hard disk This file provides an example of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file which includes...

Page 366: ...ered behind clip2_mc because it was assigned a lower depth value container_mc attachMovie symbolID clip1_mc 10 container_mc attachMovie symbolID clip2_mc 15 Depth values for movie clips can range from...

Page 367: ...or the edit_mc movie clip Do not use MovieClip getNextHighestDepth with components instead use the depth manager For more information see DepthManager class in the Component Language Reference For mor...

Page 368: ...e clip instances can swap depths at runtime To swap movie clip depths 1 Create a new Flash document called swap fla 2 Draw a blue circle on the Stage 3 Select the blue circle and then select Modify Co...

Page 369: ...e entire rectangle in Flash Player 7 and earlier In Flash Player 8 you can cache specified movie clips and buttons to improve the performance of your SWF file The movie clip or button is a surface ess...

Page 370: ...or the instance which is a cached bitmap instead of vector data If you change the bounds of the movie clip the surface is recreated instead of resized For more information and an example see Caching a...

Page 371: ...ld be used and when to use regular movie clips Overall performance of cached data depends on how complex the vector data of your instances are how much of the data you change and whether or not you se...

Page 372: ...mples and Tutorials Samples ActionScript CacheBitmap On the Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript CacheBitmap You can also find a...

Page 373: ...ster A surface cached bitmap is not created even if cacheAsBitmap is set to true if one or more of the following occurs The bitmap is greater than 2880 pixels in height or width The bitmap fails to al...

Page 374: ...istener Object new Object mouseListener onMouseDown function Void var star_mc MovieClip for var i Number 0 i star_array length i star_mc star_array i star_mc cacheAsBitmap star_mc cacheAsBitmap Mouse...

Page 375: ...utorials Samples ActionScript FlashType On the Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript FlashType Setting the background of a movie c...

Page 376: ...another movie clip are visible The mask movie clip plays all the frames in its timeline the same as a regular movie clip You can make the mask movie clip draggable animate it along a motion guide use...

Page 377: ...later When you use a movie clip to mask text set in a device font the rectangular bounding box of the mask is used as the masking shape That is if you create a nonrectangular movie clip mask for devi...

Page 378: ...never you create an instance of the movie clip to which the class is assigned it assumes the properties and behaviors defined by the class assigned to it For more information about ActionScript 2 0 se...

Page 379: ...file as ball fla in the BallTest directory the same directory that contains the MoveRight as file 8 Test the Flash document Control Test Movie Each time you click the ball movie clip it moves 20 pixe...

Page 380: ...Create a new Flash document and save it as MoveRightDistance fla in the same directory as the class file 5 Create a movie clip symbol that contains a vector shape such as an oval and then delete any...

Page 381: ...ication in several ways such as sending them to a server and retrieving a response parsing strings in an array or validating strings that the user types into a text field This chapter describes severa...

Page 382: ...a text field or within a user interface component Text fields A visual element on the Stage that lets you display text to a user Similar to an input text field or text area form control in HTML Flash...

Page 383: ...se TextArea or TextInput components to display or capture text in your applications The TextArea component is similar to a dynamic text field with built in scroll bars The TextInput component is simil...

Page 384: ...t tool in Flash You use the methods and properties of this class to control text fields at runtime TextField objects support the same properties as MovieClip objects with the exception of the _current...

Page 385: ...t field at runtime To assign text to a text field at runtime 1 Using the Text tool create a text field on the Stage 2 With the text field selected in the Property inspector Window Properties Propertie...

Page 386: ...ed 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 Acti...

Page 387: ...is reduces the chances of a variable name conflict which could result in unexpected behavior at runtime You can find sample source files that demonstrate how to work with text fields using ActionScrip...

Page 388: ...ed with createTextField The removeTextField method does not work on a text field placed by the timeline during authoring For more information see createTextField MovieClip createTextField method and r...

Page 389: ...strate 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 t...

Page 390: ...tioned to the center of the Stage To resize a text field using ActionScript 1 Create a new Flash document and save it as resizeText fla 2 Add the following ActionScript to Frame 1 of the Timeline this...

Page 391: ...the my_txt wordWrap property to false the text field resizes horizontally to accommodate the text To enforce a maximum height on the auto sized text field so that the text field height doesn t exceed...

Page 392: ...ites you might not have a choice for the format of the data that you need to load Each way of loading and or sending data to and from a SWF file has its pros and cons XML web services and Flash Remoti...

Page 393: ...to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript FlashType Using FlashVars to load and display text Using FlashVars is simple but requires you to publish your...

Page 394: ...omas 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...

Page 395: ...t src else my_txt text Unable to load external file lorem_lv load http www helpexamples com flash lorem txt The first block of code in the previous snippet creates a new text field on the Stage and en...

Page 396: ..._txt multiline true my_txt wordWrap true var lorem_lv LoadVars new LoadVars lorem_lv onLoad function success Boolean Void if success my_txt text dayNames lorem_lv dayNames n n my_txt text monthNames l...

Page 397: ...reviews_xml onLoad function success Boolean Void if success var childItems Array reviews_xml firstChild childNodes for var i Number 0 i childItems length i my_txt text childItems i firstChild firstChi...

Page 398: ...ets 1 Create a new Flash document and save it as embedding fla 2 Create a dynamic text field on the Stage by using the Text tool 3 Click Embed to launch the Character Embedding dialog box 4 Select a s...

Page 399: ...sets will embed in the Flash document as well as how many glyphs per character set specify specific characters to embed and tells you the total number of glyphs being embedded for this text field 4 Ty...

Page 400: ...box of the Font Symbol Properties dialog box 4 Select a font from the Font menu or type the name of a font in the Font text box 5 Select Bold Italic or Alias text if you want to apply a style to the f...

Page 401: ...languages 6 Select the individual characters or character sets you want to embed and then click OK to apply the changes and return to your document 7 Select Control Test Movie to test the Flash docum...

Page 402: ...racters that they contain Before you create a custom character set you should understand the necessary XML structure The following XML nodes define the Uppercase A Z character set glyphRange name Uppe...

Page 403: ...e following XML code directly before the closing fontEmbeddingTable node glyphRange name Uppercase and Numerals A Z 0 9 id 100 range min 0x0020 max 0x0020 range min 0x002E max 0x002E range min 0x0030...

Page 404: ...the period are already included in your custom character set Using TextField methods with embedded fonts Methods of the TextField class provide useful functionality for your applications For example y...

Page 405: ...a deserunt mollit anim id est laborum lorem_txt wordWrap true 2 var style_fmt TextFormat new TextFormat style_fmt font Times embedded style_fmt size 30 lorem_txt setTextFormat style_fmt 3 var mouseLis...

Page 406: ...anti aliasing to your text fields This technology is discussed in more detail later in this section Anti aliasing lets you smooth text so that the edges of characters displayed onscreen look less jag...

Page 407: ...and custom anti alias features do not support the following Flash Player 7 or earlier Skewed or flipped text Printing File exporting to the PNG file format A sample file on your hard disk shows how to...

Page 408: ...with the most legible text This option produces the largest SWF file size because it includes font outlines and also special anti aliasing information Custom Anti Alias The same as Anti Alias for Rea...

Page 409: ...he following example To use advanced anti aliasing 1 Create a new Flash document and save it as antialiastype fla 2 Create two movie clips on the Stage and give them instances names of normal_mc and a...

Page 410: ...onRelease function my_txt antiAliasType advanced The preceding code is separated into four key areas The first block of code creates a new TextFormat object which specifies a font and font size to be...

Page 411: ...y and smoothly when you use the cacheAsBitmap property 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 Macromedi...

Page 412: ...e fonts advanced anti aliasing settings are provided only for the font sizes from 6 to 20 For these fonts all sizes below 6 use the settings for 6 and all sizes above 20 use the settings for 20 Other...

Page 413: ...m_lv LoadVars new LoadVars lorem_lv onData function src String Void if src undefined my_txt text src n n src else trace error downloading text file lorem_lv load http www helpexamples com flash lorem...

Page 414: ...on formatting text see About formatting anti alias text on page 414 For more information on the TextFormat class see Using the TextFormat class on page 419 and TextFormat in the ActionScript 2 0 Lang...

Page 415: ...Timeline var my_fmt TextFormat new TextFormat my_fmt size 24 my_fmt font Arial 24 this createTextField lorem_txt 10 0 20 Stage width Stage height 20 lorem_txt setNewTextFormat my_fmt lorem_txt text lo...

Page 416: ...eld and the current values are displayed in the debug_txt text field 8 Select Control Test Movie to test the document Move the mouse pointer along the x axis to change the text field s sharpness Move...

Page 417: ...itor The subpixel setting is generally good for right aligned and center aligned dynamic text and it is sometimes a useful trade off for animation versus text quality The following example shows how t...

Page 418: ...e pixel_txt gridFitType pixel pixel_txt multiline true pixel_txt selectable false pixel_txt setNewTextFormat my_fmt pixel_txt text loading pixel_txt wordWrap true this createTextField subpixel_txt 30...

Page 419: ...tFormat class to set the formatting properties of a text field The TextFormat class incorporates character and paragraph formatting information Character formatting information describes the appearanc...

Page 420: ...character formatting txt_fmt bold true txt_fmt italic true txt_fmt size 24 5 Apply the TextFormat object to the text field you created in step 1 by using TextField setTextFormat myText_txt setTextFor...

Page 421: ...t underline false url For a complete list of TextFormat methods and their descriptions see TextFormat in the ActionScript 2 0 Language Reference Formatting text with Cascading Style Sheet styles Casca...

Page 422: ...Language Reference Add styles to the style sheet object either by loading them from an external CSS file or by creating new styles with ActionScript Assign the style sheet to a TextField object that...

Page 423: ...the value is used Units px pt are not parsed pixels and points are equivalent text decoration textDecoration Recognized values are none and underline margin left marginLeft Only the numeric part of th...

Page 424: ...pt 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...

Page 425: ...Open the Actions panel Window Actions 7 Add the following code to the Actions panel var styles TextField StyleSheet new TextField StyleSheet styles onLoad function success Boolean Void if success dis...

Page 426: ...amples 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...

Page 427: ...text field s associated variable Any text assigned to the text field s text property htmlText property or associated variable is stored verbatim anything written to one of these properties can be ret...

Page 428: ...e style sheet object myTextArea styleSheet styles myTextArea html true var myVars LoadVars new LoadVars Define onData handler and load text to be displayed myVars onData function myStr String Void if...

Page 429: ...asized style adds a font weight rule to these rules The word emphatic will be formatted using a combination of the rules specified by mainBody and emphasized Using style classes You can create style c...

Page 430: ...tags can be styled and how each style is applied Style name How the style is applied p Affects all p tags body Affects all body tags The p style if specified takes precedence over the body style li A...

Page 431: ...d the following style sheet definition to the file p color 000000 font family Arial Helvetica sans serif font size 12px display inline a link color FF0000 a hover text decoration underline headline co...

Page 432: ...tions panel this createTextField news_txt 99 50 50 450 300 news_txt border true news_txt html true news_txt multiline true news_txt wordWrap true Create a new style sheet and LoadVars object var myVar...

Page 433: ...rary XML formatted text directly to a text field so that the text is automatically formatted using the rules in the style sheet For example the following style sheet creates the new styles sectionHead...

Page 434: ...m the Text Type menu select Multiline from the Line Type menu select the Render Text as HTML option and type news_txt in the Instance Name text box 5 On Layer 1 in the Timeline Window Timeline select...

Page 435: ...owing the code in step 6 This code loads the story xml document assigns the style sheet object to the text field s styleSheet property and assigns the XML text to the text field var my_xml XML new XML...

Page 436: ...page 437 About supported HTML entities on page 444 About embedding images SWF files and movie clips in text fields on page 445 Required properties and syntax for using HTML formatted text To use HTML...

Page 437: ...align left This uses single quotes p myField_txt htmlText p align left This uses escaped double quotes p myField_txt htmlText p align left This uses outer single quotes p myField_txt htmlText p align...

Page 438: ...ref http www macromedia com target _blank Go home a You can use the special asfunction protocol to cause the link to execute an ActionScript function in a SWF file instead of opening a URL For more in...

Page 439: ...he size of the font in pixels as shown in the following example myText_txt htmlText font size 24 color 0000FF This is blue 24 point text font You can also use relative point sizes instead of a pixel s...

Page 440: ...l alignment of the embedded image within the text field Valid values are left and right The default value is left hspace Specifies the amount of horizontal space that surrounds the image where no text...

Page 441: ...ght side of the text field p The following example uses the class attribute to assign a text style class to a p tag var myStyleSheet TextField StyleSheet new TextField StyleSheet myStyleSheet setStyle...

Page 442: ...ding Specifies the amount of leading vertical space between lines corresponds to TextFormat leading Lets you use negative integers See leading TextFormat leading property in the ActionScript 2 0 Langu...

Page 443: ...r rowHeaders String b Name tAge tOccupation b Creates rows with data var row_1 String Rick t33 tDetective var row_2 String AJ t34 tDetective Sets two tabstops at 50 and 100 points table_txt htmlText t...

Page 444: ...xt autoSize left my_txt html true my_txt htmlText The lt b gt tag makes text appear b bold b At runtime the previous code example in Flash displays the following text on the Stage The b tag makes text...

Page 445: ...NG or SWF file in the img tag s src attribute For example the following example inserts a GIF file that s located in the same directory as the SWF file a relative address on or offline Embedding an im...

Page 446: ...ip into a text field 1 Create a new Flash document and save it as embeddedmc fla 2 Draw a new shape on the Stage or select File Import Import to Stage and select an image that is roughly 100 pixels wi...

Page 447: ...assign an instance name to the movie clip that is created This lets you control that movie clip with ActionScript The movie clip that Flash creates is added as a child movie clip to the text field tha...

Page 448: ...the fully qualified path to the newly created movie clip is textField_txt animation_mc 13 Save your changes to the Flash document and then select Control Test Movie to preview the animation within the...

Page 449: ...ntext menu or by pressing Shift and double clicking the text field handle You can use the scroll and maxscroll properties of the TextField object to control vertical scrolling and the hscroll and maxh...

Page 450: ...enter the following code to scroll the text down in the text field down_btn onPress function textField_txt scroll 1 6 Following the ActionScript in step 5 enter the following code to scroll the text...

Page 451: ...to encode languages Unicode is the standard for character sets that can represent any language set It is a standard that exists to help development in multiple languages The character code designates...

Page 452: ...cters in strings on page 460 Converting and concatenating strings on page 464 Returning substrings on page 467 About the Strings panel The Strings panel lets you create and update multilingual content...

Page 453: ...guage of string ID replacement You can use the properties and methods of the Locale class when you want to replace the string IDs by using ActionScript to control the application when it plays in Flas...

Page 454: ...pulated with a sorted array of available languages Whenever the lang_cb value changes Flash s event dispatcher triggers the langListener function which loads the specified language XML file The second...

Page 455: ...Mode method You can set it with the System IME setConversionMode method You can also disable or enable the IME by using your application at runtime and perform other functions depending on the user s...

Page 456: ...ple To enable and disable an input method editor at runtime 1 Create a new Flash document and save it as ime2 fla 2 Create two button symbol instances on the Stage and give them the instance names ena...

Page 457: ...ew IME If you click the disable_btn button on the Stage Flash reverts to using the previous language and ignores the current IME settings For information on System capabilities hasIME see hasIME capab...

Page 458: ...ing 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 Ma...

Page 459: ...double straight quotation mark delimiters within a single string literal use the backslash character to escape the character The following two strings are equivalent var firstStr String That s fine va...

Page 460: ...g has a length property which is equal to the number of characters in the string var companyStr String macromedia trace companyStr length 10 An empty string and a null string both have a length of zer...

Page 461: ...represents a lowercase h and the ASCII value 32 represents the space character You can also use the String fromCharCode method to convert Unicode values although the unicode value must be converted f...

Page 462: ...About using operators with strings on page 182 You can use these operators with conditional statements such as if and while The following example uses operators and strings to make a comparison To co...

Page 463: ...compare values To force strict data type comparisons 1 Create a new Flash document and save it as comparestrict fla 2 Add the following ActionScript to Frame 1 of the main Timeline var str1 String 4...

Page 464: ...reate a new Flash document and save it as convert fla 2 Type the following code on Frame 1 of the Timeline var myStr String Dr Bob Roberts 9 trace myStr toLowerCase dr bob roberts 9 trace myStr toUppe...

Page 465: ...rom Paris 3 Select Control Test Movie to test the Flash document If you use the addition operator or the addition and assignment operator with a string and a nonstring object ActionScript automaticall...

Page 466: ...erators with strings see About using operators with strings on page 182 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...

Page 467: ...as trace myStr substr 11 15 Paris Texas trace myStr substring 11 15 Pari The first method substr returns a string 15 characters long starting from the eleventh character The second method substring re...

Page 468: ...trace myStr lastIndexOf the 29 21 The lastIndexOf method finds the last occurrence of a substring in the string For example instead searching for a character or substring from the beginning of a strin...

Page 469: ...rawing API which consists of the drawing methods in the MovieClip class to add animation and draw These methods let you use code to create lines fills and shapes instead of using the drawing tools in...

Page 470: ...describe how to script animations About animation and frame rate on page 471 Fading objects with code on page 472 Adding color and brightness effects with code on page 474 Moving objects with code on...

Page 471: ...aises the total file size of your animation A 5 second animation at 24 fps typically has a higher file size than a 5 second animation at 12 fps Use the lowest possible frame rate that makes your anima...

Page 472: ...xt box in the Property inspector 6 Select Frame 1 of the Timeline and add the following code to the Actions panel img1_mc onEnterFrame function img1_mc _alpha 5 if img1_mc _alpha 0 img1_mc _visible fa...

Page 473: ...on In this code example the user defined fadeImage function is called every 50 milliseconds 20 times per second The fadeImage function decrements the value of the current movie clip s _alpha property...

Page 474: ...ransform import flash geom ColorTransform var imageClip MovieClip this createEmptyMovieClip imageClip 1 var clipLoader MovieClipLoader new MovieClipLoader clipLoader loadClip http www helpexamples com...

Page 475: ...addListener mcl_obj img_mcl loadClip http www helpexamples com flash images image1 jpg img_mc The preceding code begins by importing the ColorMatrixFilter class and creates a listener object that wil...

Page 476: ...mage brightness to 100 using the ColorMatrixFilter filter 3 Select Control Test Movie to test the document The image that you load into the SWF file changes its brightness when you test the SWF file V...

Page 477: ...following code to the Actions panel Create a movie clip instance this createEmptyMovieClip img1_mc 10 var mcl_obj Object new Object mcl_obj onLoadInit function target_mc MovieClip Void target_mc _x St...

Page 478: ...e 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 ActionScrip...

Page 479: ...ptyMovieClip img_mc 10 create a clip to use as a mask this createEmptyMovieClip mask_mc 20 use the Drawing API to draw create a mask with mask_mc beginFill 0xFF0000 0 moveTo 0 0 lineTo 300 0 lineTo 30...

Page 480: ...Loader instance specifies the listener object you created earlier and begins loading the JPEG image into the img_mc movie clip 4 Select Control Test Movie to test the document The image loads and then...

Page 481: ...ia 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 flasht...

Page 482: ...48 TransitionManager class in the Components Language Reference For information on working with packages see Working with filter packages on page 499 You can find a sample source file that uses these...

Page 483: ...Select Flash Slide Presentation from the General tab and click OK 3 Select Window Behaviors to open the Behaviors panel 4 Click Add Behavior 5 Select Screen Transition from the pop up menu to open th...

Page 484: ...before it arrives at a full stop at the end of the animation There are many equations for this acceleration and deceleration which change the easing animation accordingly The following table describe...

Page 485: ...animation The following procedure animates a movie clip so that it uses the TransitionManager class to zoom in on the Stage To animate a movie clip using the TransitionManager class 1 Select File New...

Page 486: ...ower right corner This is different from the preview you see in the Transitions dialog box Creating complex animations is easy using the Tween and TransitionManager classes and doesn t require you to...

Page 487: ...ass see Chapter 51 Tween class in the Components Language Reference For information on each method and property of the TransitionManager class see Chapter 48 TransitionManager class in the Components...

Page 488: ...he ActionScript refers to the easeOut method within the Bounce as class This ActionScript file is in the easing folder Transition Description Back Extends the animation beyond the transition range at...

Page 489: ...meter names and types function Tween obj prop func begin finish duration useSeconds code obj The movie clip object that the Tween instance targets prop A string name of a property in obj to which the...

Page 490: ...x axis before using a fluid motion effect to animating back You can find a sample source file that adds scripted animation using these classes Find tweenProgress fla in the Samples folder on your har...

Page 491: ...ing classes mx transitions easing Elastic easeOut for example you can type Elastic easeOut in your ActionScript code For more information see Working with filter packages on page 499 Using similar cod...

Page 492: ...ding the instance for three seconds it fades the instance across 24 frames 5 Select Control Test Movie to see the animation Wait a moment then the instance fades out across 24 frames 6 Return to the a...

Page 493: ...st Movie to see the animation Wait for a moment and then the instance fades out When it finishes tweening you see the message appear in the Output panel For more information on functions see Chapter 7...

Page 494: ...x transitions Tween import mx transitions easing var ball_tween Object new Tween ball_mc _x Regular easeIn 0 300 3 true ball_tween onMotionFinished function ball_tween continueTo 0 3 This code moves t...

Page 495: ...x_mc _x Regular easeInOut 0 Stage width 3 true box_tween onMotionFinished function box_tween yoyo This code creates a new tween to animate the box_mc movie clip across the Stage along the x axis over...

Page 496: ...nManager and Tween classes together 1 Create a new Flash document and save the file as combination fla 2 Add the following ActionScript on Frame 1 of the Timeline import mx transitions import mx trans...

Page 497: ...lling the createEmptyMovieClip method 3 Save your document and select Control Test Movie to view the animation in the test environment After the external JPEG image finishes downloading from the serve...

Page 498: ...ge 527 These filters are applied to the vector definitions so there is no overhead of storing a bitmap image within the SWF file You can also write ActionScript that lets you modify an existing filter...

Page 499: ...to object instances and BitmapData instances on page 503 About error handling performance and filters on page 504 For an example of using ActionScript to apply filters you can find a sample source fil...

Page 500: ...within a package such as the BlurFilter DropShadowFilter and GlowFilter you can use one of two ways to import each class The first way to import multiple classes is to import each class by using a sep...

Page 501: ...itmap is used as a source image for the filter effects Each movie clip usually has two bitmaps one bitmap is the original unfiltered source movie clip the second bitmap is the final image after filter...

Page 502: ...code applies a drop shadow filter to the square Next the code creates a temporary array to hold the current filters to apply to the red square on the Stage The distance property of the first filter is...

Page 503: ...f the instance itself is scaled _xscale and _yscale are not 100 the filter effect does not scale with the instance This means that the original shape of the instance rotates scales or skews however th...

Page 504: ...urces Therefore you should avoid using an excessive number of filters and use a lower quality setting when possible You can also encounter errors if you use invalid parameter types Some filter paramet...

Page 505: ...w Flash document and save it as transparentImg fla 2 Add the following ActionScript to Frame 1 of the Timeline import flash filters GlowFilter System security allowDomain http www helpexamples com var...

Page 506: ...523 Using the color matrix filter on page 525 Using the convolution filter on page 527 Using the displacement map filter on page 528 For an example of using ActionScript to apply filters you can find...

Page 507: ...The blur filter is based on a box pass blur filter The quality parameter defines how many times the blur should be repeated three passes approximates a Gaussian blur filter For more information on thi...

Page 508: ...ip http www helpexamples com flash images image1 jpg img_mc var blur BlurFilter new BlurFilter 10 10 2 var mouseListener Object new Object mouseListener onMouseMove function Void Moving the pointer to...

Page 509: ...sing the blur filter on page 507 Several options are available for the style of the drop shadow including inner or outer shadow and knockout mode For more information on the drop shadow filter see Dro...

Page 510: ...a filter var dropShadow DropShadowFilter new DropShadowFilter 4 45 0x000000 0 4 10 10 2 3 var mouseListener Object new Object create and apply a listener that controls the filter when the mouse moves...

Page 511: ...ong the y axis to change the amount of blur applied to the movie clip instance You can also create drop shadows and apply them to dynamically loaded images The following procedure demonstrates how you...

Page 512: ...ar p2 Number img_mc _x _xmouse var degrees Number Math atan2 p1 p2 Math PI 180 dropShadow distance Math sqrt Math pow p1 2 Math pow p2 2 0 5 dropShadow blurX dropShadow distance dropShadow blurY dropS...

Page 513: ...vieClip logo_mc 10 var my_mcl MovieClipLoader new MovieClipLoader my_mcl addListener mclListener my_mcl loadClip http www helpexamples com flash images logo png logo_mc This ActionScript code uses the...

Page 514: ...MovieClip shapeClip 10 with shapeClip beginFill 0xFF0000 100 moveTo 0 0 lineTo 100 0 lineTo 100 100 lineTo 0 100 lineTo 0 0 endFill shapeClip _x 100 shapeClip _y 100 shapeClip onPress function Void gl...

Page 515: ...ter class lets you create a gradient glow effect for a variety of objects in Flash A gradient glow is a realistic looking glow with a color gradient that you can specify You can apply a gradient glow...

Page 516: ...eDown function Void gradientGlow strength shapeClip filters gradientGlow mouseListener onMouseMove function Void gradientGlow blurX _xmouse Stage width 255 gradientGlow blurY _ymouse Stage height 255...

Page 517: ...s you add a bevel effect to a variety of objects in Flash A bevel effect gives objects a three dimensional look You can customize the look of the bevel with different highlight and shadow colors the a...

Page 518: ...100 click the mouse to increase the strength shapeClip onPress function Void bevel strength 2 shapeClip filters bevel define a listener to modify the filter when pointer moves var mouseListener Object...

Page 519: ...g 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 high...

Page 520: ...cepts of highlight color and shadow color you can apply the same concepts to understand the gradient bevel filter you have a highlight gradient and a shadow gradient The highlight appears on the top l...

Page 521: ...dient colors are applied to the object meaning where the highlight and shadow appear on the object The colors are applied in the same order as the array The following code takes a pink square drawn wi...

Page 522: ...nal movie clip color is pink but setting the 128 value to red means the 128 pixel value is the base fill and covers the original movie clip fill However when you set the filters property the original...

Page 523: ...entBevel GradientBevelFilter new GradientBevelFilter 8 225 colors alphas ratios 16 16 1 3 2 inner false apply the filter to the square movie clip square_mc filters gradientBevel Applying a gradient be...

Page 524: ...5 3 var mouseListener Object new Object mouseListener onMouseDown function gradientBevel strength shapeClip filters gradientBevel mouseListener onMouseMove function gradientBevel blurX _xmouse Stage w...

Page 525: ...1 Create a new Flash document and save it as brightness fla 2 Add the following ActionScript to Frame 1 of the Timeline import flash filters ColorMatrixFilter System security allowDomain http www hel...

Page 526: ...Clip Void center movie clip instance on Stage target_mc _x Stage width target_mc _width 2 target_mc _y Stage height target_mc _height 2 target_mc watch brightness brightnessWatcher target_mc animate t...

Page 527: ...ete the animation is reversed using the Tween yoyo method which causes the tween to constantly animate Using the convolution filter The ConvolutionFilter class applies a matrix convolution filter effe...

Page 528: ...arated into three sections The first section imports two classes ConvolutionFilter and BitmapData The second section creates a nested movie clip and uses a movie clip loader object to load an image in...

Page 529: ...erlinBmp new BitmapData target_mc _width target_mc _height perlinBmp perlinNoise target_mc _width target_mc _height 10 Math round Math random 100000 false true 1 false displacementMap new Displacement...

Page 530: ...ealistic shadows blurs and glows that react to mouse movements or user events For examples of how to manipulate filters with code see the following topics Adjusting filter properties on page 530 Anima...

Page 531: ...t a movie clip s filter properties 1 Create a new Flash document and save it as adjustfilter fla 2 Add the following ActionScript to Frame 1 of the Timeline import flash filters BlurFilter this create...

Page 532: ...e To animate blurs using the Tween class 1 Create a new Flash document and save it as animatedfilter fla 2 Add the following ActionScript to Frame 1 of the Timeline import flash filters BlurFilter imp...

Page 533: ...need to duplicate the filter using the clone method If you do not use the clone method to duplicate a filter Flash creates a reference to the original filter only If Flash creates a reference to the...

Page 534: ...u create arbitrarily sized transparent or opaque bitmap images then manipulate them in various ways at runtime When you manipulate a BitmapData instance directly by using ActionScript you can create v...

Page 535: ...autoSize left function onMouseMove status_txt _x _xmouse status_txt _y _ymouse 20 updateAfterEvent this createEmptyMovieClip img_mc 10 img_mc loadMovie http www helpexamples com flash images image1 j...

Page 536: ...d clip var shapeClip MovieClip this createEmptyMovieClip shapeClip 1 shapeClip createEmptyMovieClip holderClip 1 Load JPEG var imageLoader MovieClipLoader new MovieClipLoader imageLoader loadClip http...

Page 537: ...time multiple graphics are merged as one shape For this reason you cannot apply different blend modes to different graphic symbols For more information on using ActionScript to apply blend modes see A...

Page 538: ...Box component instance onto the Stage and give it an instance name of blendMode_cb 3 Add the following ActionScript to Frame 1 of the Timeline var blendMode_dp Array new Array blendMode_dp push data a...

Page 539: ...ange cbListener This ActionScript code populates the combo box with each type of blending mode so the user can view each effect on the dynamically loaded image A listener object is created which is us...

Page 540: ...sing a vector renderer 6 If you apply external masking layers the layers perform masking using a vector renderer Drawing with ActionScript You can use methods of the MovieClip class to draw lines and...

Page 541: ...shapes You can use the Flash Drawing API to dynamically create shapes on the Stage at runtime You can use these shapes to dynamically mask content apply filters to them or animate them around the Sta...

Page 542: ...ircle under Drawing specific shapes on page 543 for code that uses eight calls to the MovieClip curveTo method to draw a more realistic circle To draw a triangle 1 Create a new Flash document and save...

Page 543: ...nt and save it as rect fla 2 Add the following ActionScript code to Frame 1 of the Timeline this createEmptyMovieClip rectangle_mc 10 rectangle_mc _x 100 rectangle_mc _y 100 drawRectangle rectangle_mc...

Page 544: ...us lineTo boxWidth cornerRadius lineTo boxWidth boxHeight cornerRadius curveTo boxWidth boxHeight boxWidth cornerRadius boxHeight lineTo boxWidth cornerRadius boxHeight lineTo cornerRadius boxHeight c...

Page 545: ...8 radius x radius y Math sin Math PI 4 radius x Math sin Math PI 4 radius y curveTo radius x Math tan Math PI 8 radius y radius x y curveTo radius x Math tan Math PI 8 radius y Math sin Math PI 4 rad...

Page 546: ...deLength 2 0 lineTo sideLength tHeight lineTo 0 tHeight lineTo sideLength 2 0 endFill The Drawing API draws an equilateral triangle on the Stage and fills it with the specified fill color and amount o...

Page 547: ...ar colors Array 0xFF0000 0x0000FF var alphas Array 100 100 var ratios Array 0 0xFF var matrix Object a 200 b 0 c 0 d 0 e 200 f 0 g 200 h 200 i 1 var spreadMethod String reflect var interpolationMethod...

Page 548: ...styles Flash 8 includes several improvements to line drawing New line parameters added in Flash Player 8 are pixelHinting noScale capsStyle jointStyle and miterLimit The following procedure demonstra...

Page 549: ...the Stage and sets their capsStyle to round square or none 3 Select Control Test Movie to test the document The different caps styles appear on the Stage at runtime Setting parameters of line styles...

Page 550: ...pixel 3 Save the Flash document and select Control Test Movie to test the SWF file Initially both the red and blue lines look exactly the same If you right click in the SWF file and select Zoom In fro...

Page 551: ...ne You can use a nonscaleable stroke in horizontal mode or vertical mode scale the line normal or use no scaling You can use one of four different modes to specify when scaling should occur and when i...

Page 552: ...square_mc 20 square_mc lineStyle 20 0xFF0000 100 true none square square_mc moveTo 0 0 square_mc lineTo lineLength 0 square_mc lineStyle 0 0x000000 square_mc moveTo 0 0 square_mc lineTo lineLength 0 s...

Page 553: ..._mc lineTo 0 lineLength miter_mc _x 50 miter_mc _y 50 var lbl TextField miter_mc createTextField label_txt 10 0 lineLength 20 lineLength 20 lbl autoSize center lbl text miter round this createEmptyMov...

Page 554: ...iter Using Drawing API methods and scripting animation You can combine the Drawing API with the Tween and TransitionManager classes to create some excellent animated results and you only have to write...

Page 555: ...created within the target_mc movie clip which contains the dynamically loaded JPEG image The Drawing API code draws a rectangle with the same dimensions as the JPEG image within this new movie clip T...

Page 556: ...w 9 slice scaling works The easiest way to explain how 9 slice scaling works is to look at an example of how 9 slice scaling works in Flash To understand scaling in Flash 1 Create a new Flash document...

Page 557: ...grow without looking like it is being stretched see the following images You can enable slice guides for 9 slice scaling in the Flash environment within the Convert to Symbol dialog box or the Symbol...

Page 558: ...ixel black stroke on the Stage 4 Select the Oval tool and draw a purple circle 50 pixels by 50 pixels with a 2 pixel black stroke on the Stage 5 Select the purple circle and drag it into the upper rig...

Page 559: ...eight 300 var toggle_button Button this createClassObject Button toggle_button 30 label scale9Grid OFF toggle true selected false toggle_button move 420 10 toggle_button setSize 120 22 toggle_button a...

Page 560: ...at the user can toggle on and off When the button is in the on state the 9 slice grid is applied If the button is in the off state the 9 slice grid is disabled 14 Save the Flash document and select Co...

Page 561: ...clip loads or unloads or when the user clicks a button or presses a key A script can consist of a single command such as instructing a SWF file to stop playing or a series of commands and statements s...

Page 562: ...age into a browser window The gotoAndPlay and gotoAndStop functions send the playhead to a frame or scene These are global functions that you can call from any script You can also use the MovieClip go...

Page 563: ...in timelines for movie clips or other objects in the document nextScene_mc onRelease function gotoAndStop Scene 2 1 Playing and stopping movie clips Unless it is instructed otherwise after a SWF file...

Page 564: ...lers attached to movie clip objects For example the following code stops the timeline of the movie clip that bears the onClipEvent handler when the clip first loads or appears on the Stage onClipEvent...

Page 565: ...o a blank browser window and passes variables_mc name and variables_mc age in the POST header to the CFM page variables_mc getURL addUser cfm _blank POST The functionality of getURL is dependent on wh...

Page 566: ...s mouse movement within the SWF file more closely The sample in this section uses a custom pointer that looks like a large arrow The power of this feature however is your ability to make the custom p...

Page 567: ...ll function when you use a custom mouse pointer It s a good idea to put the custom pointer on the top layer of the timeline so that as you move the mouse in the SWF file the custom pointer appears in...

Page 568: ...ovie clip To get the current pointer position 1 Create two dynamic text fields and name them box1_txt and box2_txt 2 Add labels for the text boxes x position and y position respectively 3 Select Windo...

Page 569: ...the user pressed The Key class does not require a constructor function to use its methods you call the methods on the class as shown in the following example Key getCode You can obtain either virtual...

Page 570: ...e the position of the car and to show the direction The following example shows how to capture keypresses to move a movie clip up down left or right on the Stage depending on which corresponding arrow...

Page 571: ...word Left should appear in the SWF file 7 Use similar code to check if the Right Up or Down Arrow key is being pressed Your complete code should look like the following example new code is in boldface...

Page 572: ...perty inspector 4 Create a button symbol named colorChip place four instances of the button on the Stage and name them red_btn green_btn blue_btn and black_btn 5 Select Frame 1 in the main Timeline an...

Page 573: ...ction colorTrans rgb 0x000000 black trans colorTransform colorTrans 9 Select Control Test Movie to change the color of the movie clip For more information about the methods of the ColorTransform class...

Page 574: ...associated with the playButton and stopButton objects start and stop the sound by using the Sound start and Sound stop methods and also play and stop the attached sound 7 Select Control Test Movie to...

Page 575: ...ndle_btn onReleaseOutside slider_mc handle_btn onRelease The startDrag parameters left top right and bottom are variables set in a movie clip action 10 Select Control Test Movie to use the volume slid...

Page 576: ...eference Detecting collisions The hitTest method of the MovieClip class detects collisions in a SWF file It checks to see if an object has collided with a movie clip and returns a Boolean value true o...

Page 577: ...atus_txt text _level0 hitTest _xmouse _ymouse true Mouse addListener mouseListener 4 Select Control Test Movie and move the pointer over the movie clip to test the collision The value true appears whe...

Page 578: ...movie clip instance for example myClip lineTo or to a level _level0 curveTo The lineTo and curveTo methods let you draw lines and curves respectively You specify a line color thickness and alpha sett...

Page 579: ...sing ActionScript If you use components to create applications it s often necessary to add bindings between those components so that you can interact with data or have components interact with each ot...

Page 580: ...l 8 You must remember to include the DataBindingClasses component in your document for it to work because that component contains the classes that you need to work with To create a binding between two...

Page 581: ...vent will trigger the binding focusOut The second endpoint you create lists only the component and property out_ti and text respectively Finally you create the binding between the two endpoints when y...

Page 582: ...omponent in_ti src property text src event focusOut var dest EndPoint new EndPoint dest component out_ti dest property text dest event focusOut new Binding src dest null true The two changes you make...

Page 583: ...e Stage and give it the instance name my_lbl 7 Create a new layer and name it actions 8 Add the following ActionScript to Frame 1 of the actions layer var srcEndPoint Object component my_ch property s...

Page 584: ...c EndPoint new EndPoint src component my_dc src property selectedDate src event change var dest EndPoint new EndPoint dest component my_lbl dest property text new Binding src dest This code creates a...

Page 585: ...othing you must implement them in a subclass of mx data binding CustomFormatter The CustomFormatter class lets you convert data types to strings and back In this case you want to convert the selectedD...

Page 586: ...adily available to Flash you encounter the following error when you check the syntax in the previous class Error path to DateFormat class DateFormat as Line 1 The class mx data binding CustomFormatter...

Page 587: ...layer and name it actions 4 Add the following code to Frame 1 of the actions layer import mx data binding this createClassObject mx controls ComboBox my_cb 1 _x 10 _y 10 this createClassObject mx cont...

Page 588: ...bject is a movie clip instance The following script is attached to Frame 1 of the main Timeline var initx Number bug_mc _x var inity Number bug_mc _y var zapped Boolean false reset_btn onRelease funct...

Page 589: ...ces the ladybug back in its starting position on the Stage resets its rotation and alpha values and resets the zapped variable to false A conditional if statement uses the hitTest method to check whet...

Page 590: ...590 Creating Interaction with ActionScript...

Page 591: ...ded at runtime This process reduces initial downloading time and also makes it easier to maintain and update the presentation Separate content from presentation This theme is common in application dev...

Page 592: ...thod of the Sound class This method lets you specify whether the MP3 file should progressively download or complete downloading before it starts to play You can also read the ID3 information embedded...

Page 593: ...rget movie clip When you load a SWF or image file into a movie clip target the upper left corner of the SWF file or image is placed on the registration point of the movie clip Because this registratio...

Page 594: ...ny ActionScript object such as a generic Object object a movie clip or a custom component The following example creates a generic listener object named loadListener and defines for itself onLoadError...

Page 595: ...s method of the ProgressBar component to display the downloading progress of a SWF file See ProgressBar setProgress in Components Language Reference To display downloading progress by using the Progre...

Page 596: ...e movie img_mc clip 8 Select File Publish Formats and make sure the SWF and HTML options are selected 9 Click Publish and find the HTML and SWF files on your hard disk They re in the same folder as pr...

Page 597: ...unexpected behavior at runtime for example if the host SWF file and the loaded SWF file both use _root to specify a variable In Flash Player 7 and later you can use the _lockroot MovieClip _lockroot...

Page 598: ...song1 mp3 true In most cases set the isStreaming parameter to true especially if you re loading large sound files that should start playing as soon as possible for example when creating an MP3 jukebox...

Page 599: ...Sound onLoad in the ActionScript 2 0 Language Reference For information on preloading MP3 files see Preloading MP3 files on page 599 For information on creating a progress bar animation when you load...

Page 600: ...the file has finished loading clear the interval polling songTrack onLoad function Void trace load complete clearInterval poll Load streaming MP3 file and start calling checkProgress songTrack loadSou...

Page 601: ...termine when ID3 tags for a downloading MP3 file are available use the Sound onID3 event handler Flash Player 7 supports version 1 0 1 1 2 3 and 2 4 tags version 2 2 tags are not supported The followi...

Page 602: ...wse 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 Sample...

Page 603: ...yer For example if you have a QuickTime or Windows Media video file you use an encoder such as Flash 8 Video Encoder or Sorensen Squeeze to convert that file to an FLV file Flash Player 7 supports FLV...

Page 604: ...Language Reference You can create FLV files by importing video into the Flash authoring tool and exporting it as an FLV file If you have Flash Professional 8 you can use the FLV Export plug in to exp...

Page 605: ...thoring tool select New Video from the pop up menu in the Library panel Window Library 2 In the Video Properties dialog box name the video symbol and select Video ActionScript controlled 3 Click OK to...

Page 606: ...e type my_video in the Instance Name text box in the Property inspector Window Properties Properties 7 Select Frame 1 in the Timeline and open the Actions panel Window Actions 8 Type the following cod...

Page 607: ...type 468 in the width text box and 60 in the height text box 4 In the Library panel Window Library select New Video from the Library options 5 In the Video Properties dialog box name the video symbol...

Page 608: ...k the new button on the Stage to enter symbol editing mode The rectangle is currently on the first Up frame of the button you created This is the Up state of the button what users see when the button...

Page 609: ...roperties To obtain the total bytes and current number of bytes loaded for an FLV file use the NetStream bytesLoaded and NetStream bytesTotal properties The following example uses the bytesLoaded and...

Page 610: ...progressBar_mc bar_mc _xscale pctLoaded if pctLoaded 100 clearInterval loaded_interval 10 Select Control Test Movie to test your code Another way to preload FLV files is to use the NetStream setBuffe...

Page 611: ...cified cue point location so you can use code to move a video player s playhead to that location You can set particular points in an FLV file where you might want users to seek For example your video...

Page 612: ...Points cycles through the cue points var cuePointArr Array metaProp p for var j Number 0 j cuePointArr length j cycle through the current cue point parameters trace t cuePoints j var currentCuePoint O...

Page 613: ...e point2 time 7 748 type navigation parameters lights middle cuePoints 2 name point3 time 16 02 type navigation parameters lights end audiocodecid 2 audiodelay 0 038 audiodatarate 96 videocodecid 4 fr...

Page 614: ...ck and TextArea components to the Stage 3 Select the TextArea component and type my_ta in the Instance Name text box in the Property inspector Window Properties Properties 4 With the TextArea componen...

Page 615: ...ith the FLVPlayback component 1 Create a new Flash document called cueFlvPb fla 2 Drag an instance of the FLVPlayback component from the Components panel Window Components to the Stage The component i...

Page 616: ...to test your code The following cue points trace in the Output panel Elapsed time in seconds 1 034 Elapsed time in seconds 2 102 For information on addASCuePoint see FLVPlayback addASCuePoint on page...

Page 617: ...2 cuePoint cuePointName three cuePointTime 3 cuePoint cuePointName four cuePointTime 4 For more information on working with the MediaPlayback component see Media components Flash Professional only on...

Page 618: ...nt from the Components panel to the Stage 6 Select the Button component and type my_button in the Instance Name text box 7 Select Frame 1 on the Timeline and type the following code in the Actions pan...

Page 619: ...your code The cuepoints flv file contains three navigation cue points one each near the beginning middle and end of the video file When you click the button the FLVPlayback instance seeks to the next...

Page 620: ...oint point2 my_button addEventListener click clickMe 10 Select Control Test Movie to test your code The cuepoints flv file contains three navigation cue points one each near the beginning middle and e...

Page 621: ...ry select New Video from the Library pop up menu 3 In the Video Properties dialog box name the video symbol and select Video ActionScript controlled 4 Click OK to create a video object 5 Drag the vide...

Page 622: ...race i t myMeta i 10 Select Control Test Movie to test your code You see the following information in the Output panel canSeekToEnd true audiocodecid 2 audiodelay 0 038 audiodatarate 96 videocodecid 4...

Page 623: ...tions might require the application octet stream subtype to be set Security issues none Published specification www macromedia com go flashfileformat Microsoft changed the way streaming media is handl...

Page 624: ...osh 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 p...

Page 625: ...Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript Tween ProgressBar Creating a progress animation for loading SWF and image files When you load large SWF or image files into a...

Page 626: ...lineTo 0 10 lineTo 0 0 endFill _xscale 0 progressBar_mc _x 2 progressBar_mc _y 2 load progress var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip progressBar_mc ba...

Page 627: ...y while loading image files into a 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...

Page 628: ...b createEmptyMovieClip stroke_mc pb getNextHighestDepth pb createTextField pos_txt pb getNextHighestDepth 0 pb_height pb_width 22 pb _x 100 pb _y 100 with pb bar_mc beginFill 0x00FF00 moveTo 0 0 lineT...

Page 629: ...iles 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...

Page 630: ...ed my_video The loaded_txt text field is dynamically created to show information about the loading progress To create a progress bar that shows loading progress 1 Create a new FLA file called flvProgr...

Page 631: ...p bar_mc progressBar_mc getNextHighestDepth with progressBar_mc bar_mc beginFill 0xFF0000 moveTo 0 0 lineTo 100 0 lineTo 100 10 lineTo 0 10 lineTo 0 0 endFill _xscale 0 progressBar_mc createEmptyMovie...

Page 632: ...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 Tutor...

Page 633: ...to upload files from the user s computer to a server and download files from a server to the user s computer Data that you load into or send from a SWF file can be formatted as XML Extensible Markup L...

Page 634: ...purchases Several ActionScript functions and methods let you pass information into and out of a SWF file Each function or method uses a protocol to transfer information and requires information to be...

Page 635: ...ta handler executes each time a fragment of the SWF file is streamed into Flash Player For example the following ActionScript loads the variables from the file myData txt into the movie clip loadTarge...

Page 636: ...barWidth 0 bar lineTo barWidth barHeight bar lineTo 0 barHeight bar lineTo 0 0 bar endFill bar _xscale 0 var stroke MovieClip pBar_mc createEmptyMovieClip stroke_mc 20 stroke lineStyle 0 0x000000 stro...

Page 637: ...e fourth section of code creates within the pBar_mc movie clip a text field that is used to display what percentage of the XML file has already loaded similar to the label on the ProgressBar component...

Page 638: ...s method loadMovie MovieClip loadMovie method and getURL MovieClip getURL method methods can communicate with server side scripts using HTTP or HTTPS protocols These functions and methods send all the...

Page 639: ...es must write out the variable and value pairs in this format so that Flash can read them This file can specify any number of variables variable and value pairs must be separated with an ampersand and...

Page 640: ...information about the download of your data although you can t access the data until it is fully downloaded The callback interface is through ActionScript methods onLoad instead of the obsolete depre...

Page 641: ...ail LoadVars new LoadVars email emailFrom emailFrom_txt text email emailTo emailTo_txt text email emailSubject emailSubject_txt text email emailBody emailBody_txt text email sendAndLoad http www yours...

Page 642: ...m the server and what the status code returned from the HTTP request was To check HTTP status with the LoadVars object 1 Create a new Flash document and save it as loadvars fla 2 Add the following Act...

Page 643: ...lue of httpStatus is set to 404 HTTP status code for Not Found The second event handler LoadVars onLoad gets called after the file has finished loading If the file successfully loaded the value of the...

Page 644: ...import flash net FileReference var myFileReference FileReference new FileReference Or you can call the FileReferenceList browse method which opens a dialog box on the user s system to prompt the user...

Page 645: ...lity to an application on page 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...

Page 646: ...ss domain security and SWF files on page 694 When calls to FileReference browse FileReferenceList browse or FileReference download are executing playback of the SWF file pauses on the following platfo...

Page 647: ...new movie clip symbol on the Stage and open the symbol for editing double click the instance to open it in symbol editing mode 8 Create a new static text field inside the movie clip and then add the...

Page 648: ...name n Upload the file to the PHP script on the server selectedFile upload http www helpexamples com flash file_io uploadFile php When the file begins to upload the onOpen method is called so notify...

Page 649: ...ctionScript code first imports the FileReference class and initializes positions and resizes each of the components on the Stage Next a listener object is defined and three event handlers are defined...

Page 650: ...tions Macromedia Flash 8 Samples and Tutorials Samples ActionScript FileUpload The following procedure requires that PHP is installed on your web server and that you have write permissions to subfolde...

Page 651: ...is moved to the temporary folder Next the file type of the uploaded file is checked to ensure that the image is a JPEG GIF or PNG If the image is a compatible image type the image is copied from the...

Page 652: ...mples and Tutorials Samples ActionScript FileUpload On the Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript FileUpload For more information o...

Page 653: ...files on your hard disk that load XML into a SWF file at runtime One sample demonstrates how to create a web log tracker by loading parsing and manipulating XML data You can find the sample source fil...

Page 654: ...sing the XML class The methods of the ActionScript XML class for example appendChild removeNode and insertBefore let you structure XML data in Flash to send to a server and manipulate and interpret do...

Page 655: ...pt and a database The password validation for the brokerage system requires two scripts a function defined on Frame 1 and a script that creates and then sends the XML objects created in the document W...

Page 656: ...his firstChild attributes status debug_txt text this firstChild switch this firstChild attributes STATUS case OK _global session this firstChild attributes SESSION trace _global session gotoAndStop we...

Page 657: ...server for the rest of the session If the password is rejected the server responds with the following message LOGINREPLY STATUS FAILURE The loginreply XML node must load into a blank XML object in th...

Page 658: ...entry in the ActionScript 2 0 Language Reference For more information on local file security see About local file security and Flash Player on page 679 You can find a sample source file login fla in t...

Page 659: ...nHTTPStatus and onLoad and loads an external XML file The onLoad event handler checks to see whether the XML file was successfully loaded and if so sends a message to the Output panel as well as trace...

Page 660: ...nguagePicker 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_LanguagePicker On the Macintosh...

Page 661: ...can be written in a programming language such as Java You can use the connect and send methods of the XMLSocket class to transfer XML to and from a server over a socket connection The connect method e...

Page 662: ...lays text regarding connection theSocket onConnect function myStatus if myStatus conn_txt text connection successful else conn_txt text no connection made data to send function sendData var myXML XML...

Page 663: ...cs Using the fscommand function on page 663 About using JavaScript to control Flash applications on page 666 About Flash Player methods on page 666 Using the fscommand function You use the fscommand f...

Page 664: ...box from a SWF file in the HTML page through JavaScript 1 Create a new FLA file and save it as myMovie fla 2 Drag two instances of the Button component to the Stage and give them the instance names wi...

Page 665: ...filename For example for the file myMovie fla the attributes would be set to myMovie 8 In the HTML file add the following JavaScript code where the document says Place your code here if command alert...

Page 666: ...or Netscape 6 2 and later you do not need to set the swliveconnect attribute to true However setting swLiveConnect to true has no adverse effects on your SWF file For more information see the swLiveCo...

Page 667: ...function on the HTML page The External API offers the following improved functionality compared with fscommand You can use any JavaScript function not only the functions that you can use with fscomma...

Page 668: ...omponent onto the Stage assign it an instance name of out_lbl position it above the out_ti TextInput instance and set the text property in the Parameters tab of the Property inspector to Sending to JS...

Page 669: ...t Flash and HTML are both selected 8 Click Publish to create the HTML and SWF files When you re finished go on to the next procedure to create the container for the SWF file Before you can test the pr...

Page 670: ...ent outForm outField value Sending to AS br input type text name outField value br input type submit value Send form form name inForm method POST action Receiving from AS br input type text name inFie...

Page 671: ...ormation about the video in an HTML text field This procedure uses the External API to achieve this functionality To build a Flash application using the External API 1 Create a new Flash document and...

Page 672: ...code property to the HTML page by calling the JavaScript updateStatus function via ExternalInterface video_ns onStatus function obj Object Void ExternalInterface call updateStatus obj code function p...

Page 673: ...ls Samples ActionScript ExternalAPI On the Macintosh browse to Macintosh HD Applications Macromedia Flash 8 Samples and Tutorials Samples ActionScript ExternalAPI In the following procedure you modify...

Page 674: ...avigator appName indexOf Microsoft 1 flashVideoPlayer isIE window videoPlayer document videoPlayer When the user clicks the play button in the form update the videoStatus text area and call the playVi...

Page 675: ...n option value clouds flv clouds flv option option value typing_long flv typing_long flv option option value water flv water flv option select input type button name selectVideo value play onClick cal...

Page 676: ...from the website select a video from the combo box and click the play button Flash plays the selected FLV file and updates the contents of the videoStatus text area within the HTML document You can f...

Page 677: ...ing with External Data on page 633 For more information on security see www macromedia com devnet security and www macromedia com software flashplayer security For more information on security in Flas...

Page 678: ...now support for a wildcard value for example System security allowDomain and System security allowInsecureDomain If a SWF file of version 7 or earlier calls System security allowDomain or System secur...

Page 679: ...cation using Flash MX 2004 or earlier that runs locally and also accesses the Internet In Flash Player 8 this application now prompts the user for permission to communicate with the Internet When you...

Page 680: ...romedia 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...

Page 681: ...oad data from anywhere 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...

Page 682: ...s without asking your permission Flash Player 8 only A dialog box might appear alerting you that a SWF file is trying to communicate with the Internet Flash Player 8 doesn t let local Flash content co...

Page 683: ...el For more information on specifying settings in the Global Security Settings panel see Specifying trusted files using the Settings Manager on page 688 For more information on the Global Security Set...

Page 684: ...to Flash Player 8 If your locally tested or deployed legacy content an old SWF file on a user s hard disk breaks because it tries to communicate with the Internet when playing in Flash Player 8 you mu...

Page 685: ...ively you can set up a configuration file inside the FlashPlayerTrust directory For more information on setting up configuration files see Creating configuration files for Flash development on page 69...

Page 686: ...See Access local files only default Access network only See Access network only 4 Click OK to continue authoring the FLA file or click Publish to create the SWF file For more information on levels of...

Page 687: ...ith network access can communicate only with other local SWF files that have network access and they can send data to servers using XML send for example In some cases access is allowed if the HTML fil...

Page 688: ...cal file system Or you can modify the configuration file to specify trusted directories on your hard disk For more information see the following sections Specifying trusted files using the Settings Ma...

Page 689: ...Global Security Settings panel click the pop up menu and select Add Location The Add Location box opens If you arrived at the Settings Manager by clicking the Settings button in a dialog box the Add L...

Page 690: ...the Internet and the local file system Creating configuration files for Flash development The Flash 8 authoring tool sets a flag on your hard disk to identify you as a developer to direct you to a sp...

Page 691: ...s Any line that begins with a punctuator with no leading space before it is treated as a comment To create a configuration file to trust a directory 1 Locate the Security folder on your hard disk 2 Cr...

Page 692: ...shplayer security About the sandboxType property Flash Player 8 s System security sandboxType property returns the type of security sandbox in which the calling SWF file is operating The sandboxType p...

Page 693: ...e About local with file system restrictions A local with file system file has not been registered using the configuration file inside the FlashPlayerTrust directory the Global Security Settings panel...

Page 694: ...omain security and SWF files By default Flash Player 7 and later versions prevent a SWF file served from one domain from reading data objects or variables from SWF files that are served from different...

Page 695: ...95 Cross domain and subdomain access between SWF files on page 696 Allowing cross domain data loading on page 702 Domain name rules for settings and local data In Flash Player 6 superdomain matching r...

Page 696: ...erent subdomains of a single superdomain In files published for Flash Player 5 or earlier there were no restrictions on cross domain or subdomain access In files published for Flash Player 6 you could...

Page 697: ...tem security allowInsecureDomain The wildcard value permits cross scripting operations where the accessing file is any file and can be loaded from any location such as global permission Wildcard permi...

Page 698: ...blished for version 7 Flash Player applies behavior that is consistent with version 7 This practice ensures that player upgrades do not change the behavior of System security allowDomain in deployed S...

Page 699: ...sendingDomain store someSite com You might also have to add statements such as these to your files if you aren t currently using them For example if your SWF file is hosted at www someSite com and yo...

Page 700: ...SWF files For two SWF files to access each other s data variables and objects the two files must originate from the same domain By default in Flash Player 7 and later the two domains must match exact...

Page 701: ...d target_mc getData This method call will fail However data swf can grant access to SWF files served from www macromedia com by using the LocalConnection allowDomain handler and the System security al...

Page 702: ...icy file is permitted to access data assets or RSLs from that server If you are loading external data you should create policy files even if you don t plan to port any files to Flash Player 7 If you a...

Page 703: ...ple foo com is considered to be part of foo com Wildcards are not allowed in IP domain specifications If you specify an IP address access is granted only to SWF files loaded from that IP address using...

Page 704: ...method in the ActionScript 2 0 Language Reference If you use the loadPolicyFile method a site administrator can place the policy file in any directory as long as the SWF files that need to use the po...

Page 705: ...ions restricted XMLSocket connections to ports 1024 and above However in Flash Player 7 7 0 19 0 and later ActionScript can inform Flash Player of a nondefault location for a policy file using System...

Page 706: ...he connection Flash Player does so upon receiving the terminating null byte A policy file served by an XML socket server has the same syntax as any other policy file except that it must also specify t...

Page 707: ...sted at sites using a secure protocol HTTPS to be accessed by files hosted at sites using an insecure protocol Depending on whether the called file is published for Flash Player 6 7 or 8 you must impl...

Page 708: ...ain com To summarize you might have to modify your files to add or change statements if you publish files for Flash Player 7 or later that meet the following conditions You implemented cross SWF file...

Page 709: ...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 You can either port the called file to Flash Player 6 and add or ch...

Page 710: ...710 Understanding Security...

Page 711: ...t and respond to runtime errors from within your script This section describes how to debug your scripts and Flash applications by using the Debugger and how to use the Output panel For more informati...

Page 712: ...breakpoints to stop the SWF file and step through ActionScript code line by line You can use the Debugger in test mode with local files or you can use it to test files on a web server in a remote loca...

Page 713: ...a SWF file from a remote location Displaying and modifying variables on page 716 Using the Watch list on page 717 Displaying movie clip properties and changing editable properties on page 719 Setting...

Page 714: ...ures that you do not want to reveal You can use a debugging password to protect your work To enable remote debugging of a SWF file 1 Select File Publish Settings 2 On the Flash tab of the Publish Sett...

Page 715: ...Debug dialog box appears 3 In the Remote Debug dialog box select Localhost or Other Machine Select Localhost if the Debug player and the Flash authoring application are on the same computer Select Oth...

Page 716: ...SWF file while it runs For example to test collision detection in a game you can enter the variable value to position a ball in the correct location next to a wall The Locals tab in the Debugger shows...

Page 717: ...can use Hello 3523 or http www macromedia com and you cannot use x 2 or eval name i The value can be a string any value surrounded by quotation marks a number or a Boolean value true or false Using t...

Page 718: ...On the Variables or Locals tab right click Windows or Control click Macintosh a selected variable and then select Watch from the context menu A blue dot appears next to the variable On the Watch tab r...

Page 719: ...ct in the SWF file while it runs Some movie clip properties are read only and cannot be changed To display a movie clip s properties in the Debugger 1 Select a movie clip from the display list 2 Click...

Page 720: ...n the Debugger and Script window are not saved in the FLA file and are valid only for the current debugging session To set or remove a breakpoint in the Actions panel or Script window during a debuggi...

Page 721: ...window Likewise you can set breakpoints in the debugger during a debug session and have the breakpoints appear in the ActionScript file if you open it in the Script window About the breakpoints XML fi...

Page 722: ...the breakpoint exists The AsBreakpoints xml file is read when you launch Flash and generated again when you shut down Flash AsBreakpoints xml is used to keep track of the breakpoints between Flash de...

Page 723: ...Step In advances the Debugger indicated by the yellow arrow into a function Step In works only for user defined functions In the following example if you place a breakpoint at line 7 and click Step I...

Page 724: ...irectly to line 8 without stepping through myFunction although the myFunction code still executes Continue leaves the line at which the player is stopped and continues playing until a breakpoint is re...

Page 725: ...py and then select Copy Clear Clears all output currently in the Output panel Find Opens a dialog box that you can use to find a keyword or phrase within the Output panel contents Find Again Attempts...

Page 726: ...you want to send the information to the Output panel The List Objects command does not list all ActionScript data objects In this context an object is considered to be a shape or symbol on the Stage...

Page 727: ...n the object to which it belongs To make these properties easily distinguishable from other variables the value of a getter setter property is prefixed with the string getter setter The value that app...

Page 728: ...rd multiline selectable scroll hscroll maxscroll maxhscroll bottomScroll type embedFonts restrict length tabIndex autoSize The List Objects command in the Debug menu during test mode lists TextField o...

Page 729: ...rCode String httpStatus Number trace error downloading image into target_mc trace t errorCode errorCode httpStatus httpStatus var img_mcl MovieClipLoader new MovieClipLoader img_mcl addListener mclLis...

Page 730: ...730 Debugging Applications...

Page 731: ...s of Using Flash cover best practices when using the Flash authoring tool The following guidelines encourage consistency for people learning how to use Flash and write ActionScript code Adopt best pra...

Page 732: ...are working with Flash you might choose to follow some or all of the recommendations You can also modify the recommendations to suit the way you work Many of the guidelines in this chapter help you d...

Page 733: ...ge 764 discusses formatting conventions that are specific to ActionScript and common in other programming languages ActionScript coding conventions on page 745 discusses coding conventions that are sp...

Page 734: ...yPelican rather than mypelican Name a file by describing the process or item such as addUser Don t use nondescriptive names for methods or variables For example if you retrieve a piece of data that is...

Page 735: ...future releases of Flash add and break case catch class continue default delete do dynamic else eq extends false finally for function ge get gt if ifFrameLoaded implements import in instanceof interf...

Page 736: ...of paramsLv contains a LoadVars object It also ensures that the LoadVars object will not be used to store numeric or string data Because strict typing relies on the var keyword you cannot add strict d...

Page 737: ...ng on page 81 Don t overuse the Object type Data type annotations should be precise to improve performance Use an Object type only when there is no reasonable alternative Keep variables as short as po...

Page 738: ...your code that you might not find if you used literals It also lets you change the value in a single place Variables should be lowercase or mixed case letters however use the following guidelines for...

Page 739: ...ming overloading refers to the ability to make your functions behave differently depending on which data types are passed into them Name methods as verbs You might concatenate the name but it should c...

Page 740: ...or phrase For example instead of member you might qualify the noun using NewMember or OldMember Do not pluralize the words you use in the class name such as Witches or BaldPirates In most cases it is...

Page 741: ...e you might have a package named Pentagons which is responsible for using the Flash drawing API to draw various kinds of pentagons in documentation examples its name would be com macromedia docs as2 P...

Page 742: ...nents 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: ...rmation on using comments in classes see Adding comments to classes on page 744 Use the following guidelines when you add comments to your code Use block comments and for multiline comments and single...

Page 744: ...entation 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 impleme...

Page 745: ...to objects on page 746 Handling scope on page 747 Structuring a class file on page 751 About using functions on page 760 Keeping your ActionScript code in one place Whenever possible put your ActionS...

Page 746: ...ached to objects is difficult to locate and the FLA files are difficult to edit ActionScript code that is attached to objects is difficult to debug ActionScript code that is written on a timeline or i...

Page 747: ...reaking your applications as you build new modules It is important to understand the difference between the global and root scopes The root scope is unique for each loaded SWF file The global scope ap...

Page 748: ...ending on where your ActionScript 2 0 code is located The following example shows relative addressing myClip onRelease function trace this _parent myButton _x All variables must be scoped except for v...

Page 749: ...mat circleClip onPress function this startDrag circleClip onRelease function this stopDrag For a class use the following format to write code class User private var username String private var passwor...

Page 750: ...duct this Create a local variable which is used to load the XML file var prodXml XML new XML prodXml ignoreWhite true prodXml onLoad function success Boolean if success If the XML successfully loads a...

Page 751: ...addition to author information and version information 2 Add your import statements if applicable 3 Write a class declaration or interface declaration such as the following UserClass 4 Include any ne...

Page 752: ...claration if the initializer is a compile time constant Declare variables before you first use them This includes loops Avoid using local declarations that hide higher level declarations For example d...

Page 753: ...it is not necessary it makes it easy to tell that a property or method belongs to a class when it has a prefix without it you cannot tell if the property or method belongs to the superclass You can al...

Page 754: ...assword to empty strings class User private var m_username String private var m_password String function User username String password String this m_username username this m_password password Delete v...

Page 755: ...var prodXml XML new XML prodXml ignoreWhite true prodXml onLoad function success Boolean if success trace loaded else trace error loading XML prodXml load products xml The following code could be the...

Page 756: ...numOfDays i trace i dayArr i This displays the following information in the Output panel 0 sun 1 mon 2 tue 3 wed 4 thu 5 fri 6 sat Using a trace statement is an efficient way to debug your ActionScrip...

Page 757: ...ethods and properties Create a new AS file called Clothes as and enter the following code class Clothes private var color String function Clothes paramColor this color paramColor trace Clothes I am th...

Page 758: ...ould call itself repeatedly which would cause the script to fail because of infinite recursion problems The Output panel would display the following error if you didn t use the super keyword Socks I a...

Page 759: ...vie circleClip circle1Clip 1 circle1Clip _x 20 circle1Clip _y Math round Math random 20 circle1Clip _alpha 15 circle1Clip createTextField labelTxt 100 0 20 100 22 circle1Clip labelTxt text Circle 1 ci...

Page 760: ...ctions on a timeline in a class file or write ActionScript that resides in a code based component and reuse them in a variety of ways If you are using ActionScript 2 0 avoid writing functions on a tim...

Page 761: ...max temp return Math floor Math random max min 1 min static function arrayMin numArr Array Number if numArr length 0 return Number NaN numArr sort Array NUMERIC Array DESCENDING var min Number Number...

Page 762: ...0 circleClip unloadMovie delete this onEnterFrame trace deleted onEnterFrame Similarly limit the use of setInterval and remember to clear the interval when you finish using it to reduce processor req...

Page 763: ...ss operator Often setting the local reference once is preferable and more efficient Assign the Array length to a variable before a loop Assign Array length to a variable before a loop to use as its co...

Page 764: ...iting return statements on page 770 Writing switch statements on page 770 Writing try catch and try catch finally statements on page 771 About using listener syntax on page 772 General formatting guid...

Page 765: ...at button in the ActionScript editor the Actions panel or Script window to indent your ActionScript code if the syntax is correct Use line breaks to make complex statements easier to read You can form...

Page 766: ...this bad size is foo n good size is foo n Put each statement on a separate line to increase the readability of your ActionScript code The following ActionScript code shows an example of this theNum Co...

Page 767: ...tatement if condition statements else if condition statements else statements When you write complex conditions it is good form to use parentheses to group conditions If you don t use parentheses you...

Page 768: ...r way to write this code This example is preferable if y 0 return x y else return 0 The shortened if statement syntax from the first example is known as the conditional operator It lets you convert si...

Page 769: ...ound trace I will execute Executing the code despite the numUsers variable can lead to unexpected results For this reason add braces as shown in the following example var numUsers Number 0 if numUsers...

Page 770: ...following ActionScript code snippet return return myCar paintColor parentheses used to make the return value obvious return paintColor paintColor defaultColor Writing switch statements All switch sta...

Page 771: ...h case B statements break case Z statements break default statements break Writing try catch and try catch finally statements Write try catch and try catch finally statements using the following forma...

Page 772: ...vt target _name boxLdr addEventListener progress ldrListener boxLdr addEventListener complete ldrListener boxLdr load http www helpexamples com flash images image1 jpg A slight variation on the first...

Page 773: ...have names 1099 This statement is not permitted in a class definition 1100 A class or interface has already been defined with this name 1101 Type mismatch 1102 There is no class with the name ClassNam...

Page 774: ...nScript 2 0 1125 Static members are not permitted in interfaces 1126 The expression returned must match the function s return type 1127 A return statement is required in this function 1128 Attribute u...

Page 775: ...s 1149 The import keyword cannot be used as a directive 1150 You must export your Flash movie as Flash 7 to use this action 1151 You must export your Flash movie as Flash 7 to use this expression 1152...

Page 776: ...urrences of the get set private public static attribute were found 1177 A class attribute was used incorrectly 1178 Instance variables and functions may not be used to initialize static variables 1179...

Page 777: ...constructor body 1195 The identifier className will not resolve to built in object ClassName at runtime 1196 The class A B ClassName needs to be defined in a file whose relative path is A B 1197 The w...

Page 778: ...e used as a method name 1211 The package name PackageName cannot also be used as a property name 1212 The ASO file for the class ClassName could not be created Please make sure the fully qualified cla...

Page 779: ...t Logical NOT Right to left and Logical AND Left to right or Logical OR Flash 4 Left to right add String concatenation formerly Left to right instanceof Instance of Left to right lt Less than string v...

Page 780: ...780 Deprecated Flash 4 operators...

Page 781: ...code values using a SWF file and key presses you can use the following ActionScript code var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAsc...

Page 782: ...F 70 70 G 71 71 H 72 72 I 73 73 J 74 74 K 75 75 L 76 76 M 77 77 N 78 78 O 79 79 P 80 80 Q 81 81 R 82 82 S 83 83 T 84 84 U 85 85 V 86 86 W 87 87 X 88 88 Y 89 89 Z 90 90 0 48 48 1 49 49 2 50 50 3 51 51...

Page 783: ...99 d 68 100 e 69 101 f 70 102 g 71 103 h 72 104 i 73 105 j 74 106 k 75 107 l 76 108 m 77 109 n 78 110 o 79 111 p 80 112 q 81 113 r 82 114 s 83 115 t 84 116 u 85 117 v 86 118 w 87 119 x 88 120 y 89 12...

Page 784: ...standard keyboard 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 96 48 Numpad 1 97 49 Numpad 2 98 50 Nump...

Page 785: ...F7 118 0 F8 119 0 F9 120 0 F10 This key is reserved by the system and cannot be used in ActionScript This key is reserved by the system and cannot be used in ActionScript F11 122 0 F12 123 0 F13 124...

Page 786: ...ng of this appendix and press the desired key to trace its key code Left Arrow 37 0 Up Arrow 38 0 Right Arrow 39 0 Down Arrow 40 0 Insert 45 0 Delete 46 127 Num Lock 144 0 ScrLk 145 0 Pause Break 19 0...

Page 787: ...Reference to determine if an element you want to use is supported by the Flash Player version you are targeting You can also determine which elements you can use by showing the Actions toolbox elemen...

Page 788: ...t supported natively by Flash Player 4 Flash 8 exports them as series approximations which creates results that are less numerically accurate In addition because of the inclusion of series approximati...

Page 789: ...sh 4 FLA files is automatically converted to r The operator in Flash 4 was used for string addition In Flash 5 and later is the bitwise AND operator The string addition operator is now called add Any...

Page 790: ...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 myMovieClip childMovieClip myVariabl...

Page 791: ...and don t need to target Flash Player 5 you should not use the information in this appendix because writing object oriented scripts using ActionScript 1 0 is deprecated Instead for information on usi...

Page 792: ...eral built in classes including the MovieClip class Sound class and others You can also create custom classes to define categories of objects for your applications Objects in ActionScript can be pure...

Page 793: ...s that inherits from another class is called a subclass A class that passes properties and methods to another class is called a superclass A class can be both a subclass and a superclass An object is...

Page 794: ...nction that creates a circle with the property radius function Circle radius this radius radius After you define the constructor function you must create an instance of the object Use the new operator...

Page 795: ...e prototype property indicates the default property values for objects created with that function Each new instance of an object has a __proto__ property that refers to the prototype property of the c...

Page 796: ...object Circle prototype is searched for getArea ActionScript finds it calls it and traces myCircleArea Defining event handler methods in ActionScript 1 0 You can create an ActionScript class for movi...

Page 797: ...rit from MovieClip class myClipClass prototype new MovieClip Now the class myClipClass inherits all the properties and methods of the MovieClip class 4 Enter code such as the following example to defi...

Page 798: ...registerClass myclipID myClipClass this attachMovie myclipID clipName 3 Creating inheritance in ActionScript 1 0 Inheritance is a means of organizing extending and reusing functionality Subclasses inh...

Page 799: ...oto__ property for the information myObject __proto__ If the property is not a property of the object s __proto__ object ActionScript looks at myObject __proto__ __proto__ and so on The following exam...

Page 800: ...ou can add getter setter properties to prototype objects If you add a getter setter property to a prototype object all object instances that inherit the prototype object inherit the getter setter prop...

Page 801: ...ameter of the function invocation needs to be explicitly controlled Normally if a function is invoked as a method of an object within the body of the function this is set to myObject as shown in the f...

Page 802: ...he parameters to be passed to any called function The parameters are specified as an Array object This is often useful when the number of parameters to be passed is not known until the script actually...

Page 803: ...o aliased text that does not use color variations to make its jagged edges appear smoother unlike anti aliased text see following definition Anti alias refers to anti aliasing characters in order to s...

Page 804: ...searches for class or interface definitions When you create a class file you need to save the file to one of the directories specified in the classpath or a subdirectory within that Classpaths exist a...

Page 805: ...ents are generated when a movie clip loads the playhead enters a frame the user clicks a button or movie clip or the user types on the keyboard Event handlers are special events that manage when the m...

Page 806: ...let you target instances you create or movie clip and button instances on the Stage For example in the following code names and studentName are instance names for two objects an array and a string var...

Page 807: ...in your ActionScript code to carry out all kinds of actions For information and an example see Writing named functions on page 207 Object code is ActionScript that you attach to instances To add obje...

Page 808: ...arentheses and braces Each of these punctuators has a special meaning in the Flash language and helps define data types terminate statements or structure ActionScript Script Assist is a new assisted m...

Page 809: ...set the value of a variable or property For example the following statement is the target path to the volume property of the object named stereoControl stereoControl volume Text is a series of one or...

Page 810: ...var x Number 5 var name String Lolo var c_color Color new Color mcinstanceName For more information on variables see About variables on page 86 Vector graphics describe images using lines and curves c...

Page 811: ...nces 42 Flash Player 762 formatting 50 publish settings 62 ActionScript 2 0 assigning ActionScript 2 0 class to movie clips 378 compiler error messages 773 ActionScript editing check syntax 55 code hi...

Page 812: ...creating 90 elements of 163 examples of 163 165 indexed 168 iterating through a multidimensional array 171 modifying 163 166 multidimensional array 170 multidimensional using a for loop 170 pass by r...

Page 813: ...ndow 720 broadcaster object 332 built in functions 205 C cacheAsBitmap property 370 caching defined 804 callback functions defined 804 writing 208 calling methods 76 caps styles about 548 setting 548...

Page 814: ...ackaging 276 inheritance example 304 initializing properties at runtime 379 instantiation 226 methods and properties 245 mx lang classes 295 naming class files 265 organizing in packages 228 overridin...

Page 815: ...defined 804 using 136 constructor functions defined 804 sample 792 writing 211 continuous stroke modulation 408 conventions naming 732 conversion functions and data types 72 converting data types 72...

Page 816: ...rmining for movie clips 368 determining instance at 367 determining next available 367 managing 366 design patterns encapsulation 261 Singleton 252 detecting collisions 576 device fonts defined 408 80...

Page 817: ...t handler mthods checking for XML data 635 event listeners 332 classes that can broadcast 333 scope 343 event model for event handler methods 330 for event listeners 333 for on and onClipEvent handler...

Page 818: ...ing scripts 677 Flash Player 8 deprecated language elements 27 new and changed ActionScript editor features 27 new and changed language elements 22 Flash Player container defined 805 Flash Video See v...

Page 819: ...ing movie clips 353 function block 208 function literal 211 in a class file 216 named function syntax 202 naming 214 nested 222 passing parameters to 218 returning values from 220 reusing 214 sample 8...

Page 820: ...nput method editor about 455 using 455 import about the statement 500 multiple classes within package 500 using wildcard 500 importing class files 239 scripts and language encoding 57 indentation in c...

Page 821: ...API 548 capsStyle and jointStyle 551 color 550 miterLimit 554 parameters 549 pixelHinting 551 scaling 551 stroke and cap styles 548 thickness 549 lines 548 linkage coding conventions 742 identifier 36...

Page 822: ...properties in Debugger 719 changing properties while playing 357 child defined 351 controlling 352 creating an empty instance 360 creating at runtime 360 creating subclasses 378 data type 76 deleting...

Page 823: ...ented programming SeeOOP objects accessing properties 297 calling methods 298 coding standards 746 creating 90 108 296 creating in Flash 108 data type 78 defined 807 fading out 472 looping through chi...

Page 824: ...ions panel 60 pinning a script 60 pinning scripts defined 808 on the Timeline 59 playing movie clips 563 pointer See cursors policy files defined 702 must be named crossdomain xml 702 See also securit...

Page 825: ...ving objects 477 panning images 478 Tween and TransitionManager classes 481 scripts about events 32 clip events 33 correcting text display problems 57 debugging 711 frame scripts 33 importing and expo...

Page 826: ...79 about 450 analyzing 460 comparing 460 comparing to other data types 463 converting and concatenating 464 converting case 464 creating 458 creating an array of substrings 466 defined 451 809 determi...

Page 827: ...edia 447 creating dynamically at runtime 386 387 default properties 421 defined 809 displaying properties for debugging 728 dynamic 383 embedding clickable images in 449 embedding movie clips in 446 e...

Page 828: ...data type 80 Unicode and Test Movie command 712 character code 451 defined 451 support 57 Universal Character Set UCS 451 unpinning scripts in the Actions panel 60 URL variables about 101 URL encoded...

Page 829: ...void data type 81 volume creating sliding control 574 W Watch tab Debugger 717 web applications continuous connection 661 while loops 160 with statement 758 word wrapping in code enabling 52 writing A...

Page 830: ...830 Index...

Reviews: