14. Using Basic ActionScripts

Introduction

Flash’s programming language is called ActionScript. ActionScript lets you create detailed instructions on how the Flash movie will perform. ActionScripts can use an event to trigger the specific action. Say you create a button, and you want the ActionScript to trigger an instruction that will stop the movie, but only when the user clicks the button object. The defined event is the user clicking his mouse, and the action would be to stop playing the movie. ActionScript is not that difficult to learn because it uses logical phrases. For example, the command to stop playing a Timeline is:

       stop() ;


That’s pretty simple, but remember that syntax is very important. For example, the ActionScript for moving to a specific frame on the Timeline is:

      gotoAndPlay(2) ;


Notice the capitalization of the letters A and P and how the words are grouped together without any spaces. ActionScript is a relatively easy language to learn, but a very precise language to code, so pay close attention to the syntax.

The good news is that once you master the language and the syntax, the full power of Flash is available to you. You can create ActionScripts that are triggered (the event) by specific data, or information typed in by a visitor. You can even create ActionScripts that are sensitive to variables such as date and time. Flash helps you by giving you functions (English-like script) and as your ActionScript skills grow, you can even create and call your own functions. Each new version of Flash moves the ActionScripting language closer and closer to JavaScript. The power of Flash is fully realized when you write ActionScripts and incorporate them in your Flash documents.

Using Object-Oriented Programming

Using Object-Oriented Programming

FL 4.2, 4.3

Objects are the key to understanding object-oriented programming. In object-oriented programming (OOP), an object is just as real as an object in this world. For example, your dog, or even your computer are objects that exist in the real world. Real-world objects share two characteristics with objects in the computer world: They have a specific state and behavior. For example, dogs have a state such as their name, color, breed, and if they’re hungry. Dog behaviors would be: barking, fetching, and wagging their tails. All objects in the real and computer worlds have a behavior and a state.

Computer objects are modeled after real-world objects in that they also have a specific state and behavior. A class is a representation of an object that stores information about its data type, state, and behaviors. A class can include three types of characteristics: properties, methods, and events. A property represents different data associated with an object. A method is an action that can be performed by an object. An event is a system, application, or user action, such as a mouse click, that triggers an action related to an object.

After you create a class, you can also create new classes based on the existing one, known as subclassing or extending a class. The subclass inherits all the properties and methods of the parent class, known as the superclass. For example, you could create a superclass called Parents, and a subclass called Children. Inheritance allows one class definition (subclass) to include all the functionality of a different class definition (superclass). You can also additional methods and properties to the subclass as well as override methods inherited from a superclass, which is called polymorphism.. Inheritance and subclassing are very useful for large projects where you can share similar functionality and reduce the amount of code.

An object maintains its state using one or more variables. A variable is an item of data named by an identifier, and an object performs its behavior with methods. Everything an object understands (its state) and what it can do (its behavior) is expressed by the variables and the methods within that object.

An object that represents a speeding car would have variables that instruct the object as to speed, direction, and color. These variables are known as instance variables because they contain the state for a particular object, and in object-oriented terminology, a particular object is called an instance. In addition to its variables, the car would have methods assigned to change speed and turn on the lights. These methods are formally known as instance methods because they inspect or change the state of a particular instance.

Using Object-Oriented Programming

Viewing the Actions Panel

The Actions panel is gives the Flash designer control of a Flash document by allowing him/her to create and edit actions for an object or frame. To use the Actions panel, select an object on the stage, or select a frame on the Timeline, click the Window menu, and then click Actions. Scripts can be typed directly into the Actions panel using the Script pane, or augmented by using a list of installed Actions in the Toolbox.

Toolbox. Supplies a list of all installed actions, organized into a folder for either ActionScript 1.0 & 2.0 or ActionScript 3.0

Script pane. Enter the Actions into the Script pane.

Script Navigator pane. Gives reference to all the Scripts in the active movie.

Current Script tag. Indicates which script is being edited.

Pin Script. Adds a tab for a selected script.

Options menu. Contains options that control and format the Actions panel.

Add Statement. Lets you add script elements to the current action.

Find, and Find and Replace. Searches the active script.

Insert Target Path. Inserts a specific target clip into the action.

Check Syntax. Checks the current action for syntax errors.

Auto Format. Cleans up the script by auto indenting.

Show Code Hint. Gives you hints to the syntax of the action as you type.

Debug Options. Add or remove breakpoints into the action to pause on the specified line of code.

Collapse and Expand. Collapse between braces, collapse selection, or expand all.

Comments. Apply a block or line comment.

Script Assist for 3.0. Script assist provides a visual interface for editing scripts that includes syntax completion and parameter descriptions.

Help. Provides online help.

Help.

Understanding Properties and Methods

Understanding Properties and Methods

FL 4.2

Objects in Flash are defined using two primary identifiers: properties and methods. The properties of an object define its characteristics. In the real world, a house would be an object, and its properties would be things like its color, style, and number of windows and doors. In Flash, it would be written something like this:

               house.color = "green";
               house.style = "ranch";
               house.windows = "12";
               house.doors = "2";


In this example, the word house is a unique instance name for the house object, and the words color, style, windows, and doors represent the properties assigned to this instance. Think of an instance as a copy of a Library item. When you create a movie clip, the object is created in Flash’s Library. When you return to the Stage, you can then drag the movie clip from the Library to the Stage (technically, you’re moving a Library symbol, created using the movie clip behavior). Once the movie clip is moved to the Stage, it is defined as an instance of the original Library item. When you select an instance on the Stage, Flash’s Properties panel lets you give it a unique name. In the previous example, “house” is the unique name.

Giving a Library symbol a unique name gives you a lot of control. For example, you could move two instances of the same movie clip onto the Stage, give each of them its own unique name (house1, house2) in the Properties panel, and then define different properties for each one. Something like this:

               house1.color = "green";  house2.color = "blue";
               house1.style = "ranch";  house2.style = "tudor";
               house1.windows = "12";   house2.windows = "8";
               house1.doors = "2";      house2.doors = "4";


As a matter of fact, you could create an entire town using one Library item. The advantage to this approach is enormous. You could create a Flash movie with 100 different instances of the same movie clip, and the Flash movie would only need to save a single copy, and then change that one copy using different properties.

In Flash, most objects have properties. For example, the MovieClip object has property values such as transparency, horizontal and vertical position, and visibility. You might define properties loosely as the physical appearance of a movie clip, as it appears on the Flash Stage. A method instructs the object to perform some task. A method is a function that is part of a class definition. For example, if a DVD player is an object, then the methods would be something like: play, record, and stop. Flash methods are written like this:

      play();
      record();
      stop();


Some methods require parameters within the parenthesis. The following method instructs the play head to move to frame 6 on the Timeline and stop:

      gotoAndStop(6);


Attaching the method to a specific object requires identifying the object in the ActionScript code:

      myDVD.gotoAndStop(6);


ActionScript is a language, and just like learning any foreign language, all the words and syntax might seem strange at first; however, the longer you work with the language, the simpler it becomes.

Introducing ActionScript 3.0

Flash 8 uses ActionScript versions 1.0 and 2.0. In CS3, Flash introduced ActionScript 3.0, a robust programming model familiar to developers with a basic knowledge of object-oriented programming. ActionScript 3.0 allows you to create highly complex applications with large data sets and object-oriented, reusable code bases. ActionScript 3.0 provides a new architecture, core language features, and an improved Flash Player API for better low-level control. Some of the enhancements include more run-time exceptions for common error conditions, added use of run-time type information, improved use of properties and classes with sealed classes, added use of method closures for event handling, added use of industry standard ECMAScript for XML, more support for regular expressions, and added primitive types (int and uint). For specific details about using an ActionScript language, click the Help menu, click Flash Help, and then look in the Programming ActionScript 2.0 or 3.0 or the ActionScript 2.0 or 3.0 Language and Components Reference online chapter.

While ActionScript 3.0 is not required for content that runs in Adobe Flash Player 9 or later, it allows performance improvements that are available only with the ActionScript Virtual Machine (AVM2). ActionScript 3.0 code can execute up to ten times faster than legacy ActionScript code.

Compatibility

The older version of ActionScript Virtual Machine (AVM1) executes ActionScript 1.0 and ActionScript 2.0 code. Flash Player 9 supports AVM1 for backward compatibility with existing and legacy content. Flash Player 7 and 8 only support AVM1 and not AVM2. However, there are a few things you need to know about compatibility. A SWF file cannot combine ActionScript 1.0 or 2.0 with ActionScript 3.0 code, and ActionScript code can load an SWF file with ActionScript 1.0 or 2.0, but it cannot access the file’s variables and functions (except you can use the loadMovieNum() command and pass a level parameter). If you have ActionScript 1.0 or 2.0 code and want to use version 3.0 code, you need to migrate all the old code to version 3.0. If you want to use behaviors, you need to use ActionScript 2.0; behaviors are not available for ActionScript 3.0.

Working with Objects and Classes

Working with Objects and Classes

FL 4.1, 4.2, 4.3, 4.4

With ActionScript 3.0, you specify a class definition, either document or object level, to work with objects using ActionScript code. To create your own class, you need to follow a certain syntax. First, you enter a package statement to indicate where your class will be found. Then, you enter a class statement to define the name of the class. At this point, you define each property in the class by using variables, and each method by using functions. When you define a class element, such as a property or method, you can also specify an attribute. A private attribute can be called only by code within the class, while a public attribute can be called by any code in the program. After you define a class, you can define a subclass that inherits all the properties and methods of the parent class, or superclass. In the subclass, you can add methods and properties and override others from the superclass, known as polymorphism. If you want to trigger actions based on events, you can use the EventDispatcher class to keep track of event listeners and notify them of events.

Work with Objects and Classes in ActionScript

Work with Objects and Classes in ActionScript Create or open a Flash document (ActionScript 3.0).

Work with Objects and Classes in ActionScript Open the Properties panel.

Work with Objects and Classes in ActionScript

Work with Objects and Classes in ActionScript Click the Stage.

Work with Objects and Classes in ActionScript In the Class field, type the name of the ActionScript file to create a document class definition.

Important

Be sure not to include the .as extension.

Important Open the Library panel.

Important

Important Right-click (Win) or Important-click (Mac) the object you want to control in ActionScript, and then click Properties.

Important Click Advanced, if available. (Button name changes to Basic.)

Important

Important Enter a name for the object.

Important Select the Export for ActionScript check box.

The Class appears with the same name as the object, and the Base class appears with object type.

Important Click OK.

Important

Important If prompted, click OK to define the new class.

Important Click the File menu, and then click Save.

Important Click the File menu, click New, and then click the General tab.

Important Click ActionScript File.

Important Click OK.

Important Click the File menu, and then click Save As.

Important Navigate to the folder with the Flash document, and then name the file (same as the one in Step 4).

Important Click Save.

Important In the Actions panel, enter the script as shown in the illustration.

Important

ActionScript 3.0 is case-sensitive, so upper- and lower-case make a difference.

Important Click the File menu, click Save, and then close the ActionScript file.

Important Click the Control menu, and then click Test Movie.

Did You Know?

You can define accessor methods. For advanced ActionScripting, you can also define accessors methods, which are a cross between a method and property (defined like a method, yet creates an instance like a property).

Applying Properties and Methods to an Object

Once you’ve gotten the hang of writing ActionScripts, the next step is to apply properties and methods to objects in a Flash document. You can have an object and let your visitor control its color. Changing the color is an example of changing an object’s properties. To make an object change color, you will need a Flash document that contains a MovieClip and button symbols. An easy script translation would be: Flash, when my visitor clicks (release) on the button, I want you to assign a new color to an object that I gave a unique instance name (change it), and I’m defining that property as objectColor, and change the color (setRGB) to red (0x990000). When you attach ActionScripts to buttons, you’re not limited to just a single use. For example, you could drag three instances of the same button symbol on the Stage and repeat the previous code with one exception: change the SetRGB value of one to (0x990000) for red, another to (0x009900) for green, and the third one to (0x000099) for blue.

Apply Properties and Methods

Apply Properties and Methods Drag the movie clip onto the Stage.

Apply Properties and Methods

Apply Properties and Methods Enter a unique instance name in the Properties panel.

Apply Properties and Methods

Apply Properties and Methods Drag the button symbol onto the Stage, and then select the symbol.

Apply Properties and Methods Click the Window menu, and then click Actions to open the Actions panel.

Did You Know?

You can now edit ActionScript code using external editor applications. MetaData (Windows), BBEdit (Macintosh), or any editor that saves files using the .as (ActionScript) extension gives you the ability to edit and save ActionScript code. The file can then be opened in Flash (click the File menu, and then click Open) or imported into the Flash Actions panel (click the Actions Options button, and then click Import Script).

You can now edit ActionScript code using external editor applications. Enter the script (ActionScript 2.0) as shown in the illustration.

• ActionScript 3.0 example files are available on the Web at www.perspection.com.

You can now edit ActionScript code using external editor applications.

You can now edit ActionScript code using external editor applications. Click the Control menu, and then click Test Movie.

You can now edit ActionScript code using external editor applications. Click the button to change the color of the object to red.

You can now edit ActionScript code using external editor applications.

Important

Button objects can have triggering events other than a user click. You can create a button instance that uses the rollover event, and have an object change color as the user rolls over the button. Or, you can create an invisible button with a rollover event that triggers a property change when the user rolls over a specific portion of the image.

See Also

See “Creating Invisible Buttons” on page 153 for information on creating invisible buttons.

Setting ActionScript Preferences

Since ActionScripting is so important, Flash gives you the ability to control the Actions panel through preferences. ActionScript preferences give you the ability to control the font and size of the text typed into the Actions panel, as well as using syntax coloring to help you visualize the code. You can also set AutoFormat preferences to specify the automatic formatting you want for your ActionScript code.

Set ActionScript Preferences

Set ActionScript Preferences Click the Flash (Mac) or Edit (Win) menu, and then click Preferences.

Set ActionScript Preferences Click the ActionScript category,

Set ActionScript Preferences

Set ActionScript Preferences Select from the following options:

Automatic Indentation. Instructs Flash to perform syntax indentation.

Tab Size. Enter a value for the number of spaces used.

Code Hints. Gives you on-screen hints as you type.

Delay. Delay before showing a code hint. Drag slider to select a value (0 to 4) in seconds.

Font. Select a font and size for the ActionScript text.

Open/Import and Save/Export. Select UTF-8 or Default encoding for open and import operations (UTF-8 is best).

Reload Modified Files. Click to be prompted when Flash needs to reload a modified file.

Syntax Coloring. Choose the syntax-coloring scheme.

Language. Click ActionScript 2.0 or ActionScript 3.0 to modify the ActionScript sub-settings.

Language. Click the Auto Format category.

Language.

Language. Select the format check boxes you want and view the effect in preview.

Language. Click OK.

Using Dot Syntax

ActionScript, just like any human language, has rules you should follow. However, in ActionScripts, you have to follow the rules or it won’t work. One of the more important rules to follow is the use of dot syntax. The use of dots (.) in a script serves several purposes. First, is to specify the target path to a particular Timeline. For example, _root.america.kansas.wichita defines a movie clip on the main (_root) Timeline with the name america, containing a movie clip named kansas, which in turn contains a movie clip named wichita. Dot syntax is used to create a road map for Flash to follow. Dot syntax is a separator between two or more parts of a Flash script.

Another use of dot syntax is to change the properties and methods for a specific object. Since ActionScript, by definition is an object-oriented language, Flash performs its responsibilities by instructing an object to do something (method), or by changing a property. For example, star._rotation = 90; instructs Flash to rotate the MovieClip instance named star, 90 degrees (property). To instruct the star MovieClip instance to play (method), you would enter the following code: star.play();

Using Dot Syntax

Applying Dot Syntax to a Movie Clip

When you use dot syntax, you gain control over a Flash ActionScript. For example, you have a movie clip of a car, and the wheels of the car are separate movie clips. In other words, you’ve dragged a movie clip symbol (the wheels), into a movie clip (the car), and you want to use a button to stop and start the wheels movie clip. To do this will require using dot syntax to identify the path to the correct movie clip, and then use the play or stop methods on the wheels.

Use Dot Syntax

Use Dot Syntax Open the file movingCar.fla, and then open the car movie clip symbol in the Flash Library.

Use Dot Syntax

See “Real World Examples” on page xviii in the Introduction for information on downloading practice files from the Web.

Use Dot Syntax Create a new layer, and then select the new layer.

Use Dot Syntax Drag the wheel movie clip symbol into the car movie clip, and then place one copy for the front and one copy for the back wheels.

Use Dot Syntax

Use Dot Syntax Select and give each of the wheel symbols a unique name in the Properties panel.

Use Dot Syntax Return to the Stage, drag the car movie symbol onto the Stage, and then select the symbol.

Use Dot Syntax

Use Dot Syntax Give the car movie symbol a unique name in the Properties panel.

Use Dot Syntax Drag the Play button symbol onto the Stage, and then select the symbol.

Use Dot Syntax Enter the script (ActionScript 2.0) as shown in the illustration.

Use Dot Syntax

Important

Transportation is the instance name of the car symbol on the Stage, and front wheel and back wheel are the instance names for the wheel movie clips as defined in the Library.

Important Drag the Stop button symbol onto the Stage, and then select the symbol.

Important Enter the script (ActionScript 2.0) as shown in the illustration.

• ActionScript 3.0 example files are available on the Web at www.perspection.com.

Important

Important Click the Control menu, and then click Test Movie.

Understanding Data Types

When you use ActionScripts, you have the ability to work with data. Data can be information entered in by a visitor in an input data field, or it can be computer information such as the current position of the mouse, or the date and time. When you work with data, you have 4 possible data types:

String. Allows for the entering of text values.

Number. Allows for the entering of numeric values.

Boolean. A Boolean state has two values; typically true or false.

Object. Serves as a storage device for any data type, including other objects.

Use Data Types to Control Information

Since data types control the type of information that can be entered into a data field, you can use them to validate the data someone is entering. For example, you want to create a calculator to convert between degrees Fahrenheit and Celsius. To do this, you will need an input field for someone to enter the current temperature in Fahrenheit, a button that would perform the calculation, and then a dynamic text field for the result, and one for an error message.

Use Data Types to Control Information Select the Input Field, and then give it a unique variable name in the Properties panel.

Use Data Types to Control Information Select the Error Dynamic Text Field and give it a unique variable name in the Properties panel.

Use Data Types to Control Information Select the Results Dynamic Text Field, and give it a unique variable name in the Properties panel.

Use Data Types to Control Information Select the button instance, and then enter a script into the Actions panel (see the example file for script details).

When the movie is played, the visitor will enter a value into the data field, and it will be evaluated as to whether it’s purely numeric. If it isn’t, an error message will display in the dynamic error field. If the field contains numbers, then the calculation will perform the conversion and display the results displayed in the output field.

Use Data Types to Control Information
Use Data Types to Control Information
Use Data Types to Control Information

Using Functions

A function is a block of ActionScript code that can be reused anywhere in a SWF file. If you pass values as parameters to a function, the function will operate on those values. A function can also return values. Flash contains built-in functions that let you access certain information and perform certain tasks, such as getting the version number of Flash Player hosting the SWF file (getVersion()). Functions that belong to an object are called methods. Functions that don’t belong to an object are called top-level functions and are found in the Functions category of the Actions panel.

Each function has its own characteristics, and some functions require you to pass certain values. If you pass more parameters than the function requires, the extra values are ignored. If you don’t pass a required parameter, the empty parameters are assigned the undefined data type, which can cause errors when you export a script. To call a function, it must be in a frame that the playhead has reached.

To call a function, simply use the function name and pass any required parameters. The following code describes a common syntax for creating functions:

      function firstFunction (x, y, z) {
        // place all actions here;
      }


Calling a Function

Functions begin with the word function, followed by the name of the function (user-defined). The area enclosed by parenthesis is used for passing parameters to the function actions. If the parameters are left blank, you’re essentially creating a generic function that will function the same way every time it’s called. If the function contains parameters, it will perform in a unique way each time it’s called. When you call a function, you’re instructing Flash to execute all of the actions within that function. Therefore, if firstFunction contained 20 actions, all of them would be executed by using a single line of script. To call a function, simply add this line to the action:

      myFunction ();


Passing Parameters to a Function

If the function has been defined to accept parameter information, you can use the following line of script:

      myFunction (parameter 1, parameter2);


Once a Function is defined, it can be called anytime it’s needed. Therefore, it’s a good practice to define all of your functions in frame 1 of the active Flash document. That way they can be called anytime after that.

Understanding Event Handlers

Event handlers, also known as event listeners, control when events in Flash occur. When you create a script, some event will be invoked to trigger that particular action.

Event Handlers with ActionScript 3.0

For ActionScript 3.0, event handlers are functions (also known as listener functions) that respond to specific events. For example

function clickHandler(event:MouseEvent):void { }


After you create a listener function, you use the addEventListener() method to register the function with the target event. For example,

addEventListener (MouseEvent.CLICK, clickHandler);


Event Handlers with ActionScript 2.0

For ActionScript 2.0, event handlers come in three different types: mouse events, frame events, and clip events. Mouse events trigger actions when the mouse interacts with a button or movie clip instance. The following events can be associated with mouse events:

on (press). The acton is triggered when the mouse is pressed.

on (press).

on (release). The action is triggered when the mouse is released.

on (releaseOutside). The action is triggered when the mouse is pressed on a object (button), and then released outside.

on (keyPress). The action is triggered when the visitor presses a key.

on (rollOver). The action is triggered when the visitor rolls over an object.

on (rollOut). The action is triggered when the visitor rolls out of an object.

on (dragOver). The action is triggered when the visitor clicks and then drags into an object.

on (dragOut). The action is triggered when the visitor clicks on an object, and then drags out.

on (dragOut).
on (dragOut).

Attaching a Mouse Event to a Button

Attaching a mouse event to a button is probably the easiest of all the event handlers. For example, you have a movie clip of a dog that contains a barking audio file. When the movie clip plays, the dog barks. The trick is to have the dog bark when the visitor rolls their mouse over the dog’s face. To do this, you will need to create an invisible button and then attach the mouse event to the invisible button.

Attach an Event to a Button

Attach an Event to a Button Click the Insert menu, and then click New Symbol.

Attach an Event to a Button Select the Button type, and then name the symbol.

Attach an Event to a Button

Attach an Event to a Button Click OK.

Attach an Event to a Button Create a blank keyframe in the Hit state of the button, and then create a shape.

Leave the Up, Over, and Down states blank.

Attach an Event to a Button Exit the Symbol editing mode, and then return to the Stage.

Attach an Event to a Button Drag a movie clip onto the Stage.

Attach an Event to a Button

Attach an Event to a Button Create a new layer, and then name the layer.

Attach an Event to a Button Drag the invisible button onto the Stage, and then place it over the area of the image you want to use as a button.

Attach an Event to a Button Enter the script (ActionScript 2.0) as shown in the illustration.

• ActionScript 3.0 example files are available on the Web at www.perspection.com.

Attach an Event to a Button

When the visitor rolls into or out of the invisible button, the rollOver or rollOut event handlers will trigger the playing or stopping of the dog movie clip.

Attach an Event to a Button Click the Control menu, and then click Test Movie.

Working with Frame Events

Frame event handlers are easy to understand. When an action is attached to a frame, the action is triggered when the play head hits the frame. For example, you want to create a frame event that swaps images on the Stage, and you want the images to swap every 40 frames. You can attach an ActionScript that swaps the image, and place the action every 40 frames. When the play head hits the frame, the action executes. When you attach an ActionScript to a frame, you’ll need a blank keyframe on the Timeline, and it is strongly recommended that you always place ActionScripts in a separate layer from access and control. In addition, if you’re planning to swap images in a Flash movie, it’s always best to use a blank movie clip (called a placeholder) to hold the images.

Attach an ActionScript to a Frame

Attach an ActionScript to a Frame Drag a blank movie clip onto the Stage, and then select the clip.

Attach an ActionScript to a Frame

Attach an ActionScript to a Frame Give the movie clip a unique instance name in the Properties panel.

Attach an ActionScript to a Frame Create a new layer, and then name the layer.

Attach an ActionScript to a Frame Create blank keyframes at frame numbers 1, 21, 41, and 61.

Attach an ActionScript to a Frame Select a frame, click the Insert menu, point to Timeline, and then click Blank Keyframe.

Attach an ActionScript to a Frame Select frame 1, and then enter the script (ActionScript 2.0) as shown in the illustration.

• ActionScript 3.0 example files are available on the Web at www.perspection.com.

Attach an ActionScript to a Frame

Attach an ActionScript to a Frame Select frames 21, 41, and 61, and then repeat the script, except change the name of the image you want to load (image_b.jpg, image_c.jpg, image_d.jpg).

Attach an ActionScript to a Frame Click the Control menu, and then click Test Movie.

Working with Clip Events

If you’re working with ActionScript 2.0 (not supported in ActionScript 3.0), you can attach clip events to movie clips, which triggers an action specified in the onClipEvent handler. You might want a specific movie clip to stop playing when another movie clip loads on the Stage, or when the user clicks or moves their mouse.

The Clip Event is one of a series of event handlers that Flash uses to create actions within a Flash movie. You can attach event handlers directly to a button or movie clip instance by using the onClipEvent() or the on() handlers. The onClipEvent() handles movie clip events, and on() handles button events. To use an on() or onClipEvent() handler, attach it directly to an instance of a button or movie clip on the Stage, and then specify the event you want to handle for that instance. For example, the following on() event handler executes whenever the user clicks the button the handler is attached to.

      on(press) {
       trace("The button has been pressed.");
      }


Working with Clip Events

You can specify two or more events for each on() handler, separated by commas. The ActionScript in a handler executes when one of the events specified by the handler occurs. For example, the following on() handler attached to a button will execute whenever the mouse rolls over or out of the button.

      on(rollOver, rollOut) {
       trace("mouse rolled in or out");
      }


If you want different scripts to run when different events occur, you have the option to attach more than one handler to an object. You can attach onClipEvent() handlers to the same movie clip instance. The first would execute when the movie clip first loads (or appears on the Stage); the second executes when the movie clip is unloaded from the Stage.

      onClipEvent(load) {
       trace("loaded");
      }
      onClipEvent (unload) {
       trace("unloaded");
      }


Working with Clip Events

Attaching a Clip Event to a Movie Clip

For ActionScript 2.0, you can only attach an onClipEvent() to a movie clip instance that has been placed on the Stage. You can’t attach an onClipEvent() to a movie clip instance that is created at runtime; for example, using the attachMovie() method. However, you can still attach multiple event handlers. Using different event handlers within the same Flash document do not conflict with each other. You could have a button with 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 Stage to rotate. When the button is clicked, the SWF file plays, and the object will rotate. Being able to consolidate different event handlers with a single instance gives you greater control, as well as less Stage clutter.

Attach an onClipEvent to a Movie Clip

Attach an onClipEvent to a Movie Clip Create or open a Flash document (ActionScript 2.0), place a movie clip on the Stage, and then select the movie clip.

Attach an onClipEvent to a Movie Clip

Attach an onClipEvent to a Movie Clip Give the movie clip a unique instance name in the Properties panel.

Attach an onClipEvent to a Movie Clip Move down the Timeline and add a keyframe at frame 80.

Attach an onClipEvent to a Movie Clip Click the Insert menu, point to Timeline, and then click Keyframe.

Attach an onClipEvent to a Movie Clip Add a second movie clip to the Stage, and then select the second movie clip.

Attach an onClipEvent to a Movie Clip Enter the script as shown in the illustration.

Attach an onClipEvent to a Movie Clip

Attach an onClipEvent to a Movie Clip Click the Control menu, and then click Test Movie.

When the playhead hits frame 80 it loads the second movie clip. The loading of the movie will trigger the onClipEvent handler, and stop the playing of the movie clip with the unique instance name of movie2.

Creating Loops

Loops allow Flash to perform an action repeatedly. You can use a loop to create a dynamic drop-down menu, validate data, search for text, duplicate movie clips, and even detect collisions in games that have projectiles and objects. Conditional statements let you execute an action based on a specific condition. You can have a specific action continue to loop until a certain condition is met. For example, continue to search for a specific text string until it is found or the end of the text document is reached. Loops come in two forms—While loops and For loops—it doesn’t matter what type of loop is chosen, they will both require a conditional statement to start and stop.

While Loops. While loops continue to execute while a certain condition exists (keep looping or searching) until a specific value is reached.

i = 4;
while (var i > 0) {
 my_mc.duplicateMovieClip("newMC" + i, i );
 i--;
}


For Loops. For loops are self-contained counters. For example, loop (repeat the action) ten times and then stop.

x = x;
for (x=0; x<=10, ++x) {
  myClip.duplicateMovieClip ("myClip" + x, x);
  myClip._rotation =45 + x * 10;
}


Working with For Loops

The For loop works with an increasing or decreasing numeric value. For example, you could use a For loop to create several copies of a movie clip on the Stage. Letting the For loop control movie clips to the Stage is far more efficient than having to move them one at a time. In addition, the visitor can control when the items appear on the Stage using a button.

Work with For Loops

Work with For Loops Drag a movie clip from the Library to the Stage, and then select the movie clip.

Work with For Loops

Work with For Loops Enter a unique instance name for the movie clip in the Properties panel.

Work with For Loops Place a button on the Stage, and then select the button.

Work with For Loops Enter the script (ActionScript 2.0) as shown in the illustration.

• ActionScript 3.0 example files are available on the Web at www.perspection.com.

Work with For Loops

When you play the movie, clicking on the button causes the action to loop 10 times. Each time it loops, it duplicates the original movie clip and rotate it by 45 degrees plus the current value of x times 10.

Did You Know?

You can use a For Loop to pause a Flash movie. Select a value, instruct the loop to increment by 1, and then loop until the value is reached. Use a loop timer for such items as a Flash slide show, where you want the slides to display on the stage for a given number of seconds before moving to the next slide.

Working with While Loops and Using Loop Exceptions

While loops wait for a specific condition to start or stop the loop. That may sound similar to the For loop, with one exception: The For Loop is self-contained, and the While loop works with an external condition, or one outside the scope of the loop. For example, to have a While loop perform the same action as the previous For loop, you would use the following script:

x = 0;
while (x<10) {
 myClip.duplicateMovieClip ("myClip" + x, x);
 myClip._rotation =45 + x * 10;
 x=x+1;
}


When you create a Looping action, you can further control the loop by using the following loop exceptions:

Continue. The continue exception lets you stop the current loop from performing its actions and jump directly to the next cycle of the loop.

Break. The break exception is used to exit a loop, even if the original condition that is driving the loop is still true.

For example, if you create a While loop using the following script:

total = 0;
i = 0:
while (++i <=20) {
 if (i == 10) {
    continue;
 }
 total +=i;
}


The results would be a script that executes and adds 1 to total; unless the value of i equaled 10. This would create a sequence of numbers 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20. If you had used the break exception in place of continue, the values would read: 1 2 3 4 5 6 7 8 9. Therefore, it loops whether For or While are controlled by internal or external conditions, and using a break or continue exception gives you further control over the loop.

Using Conditional Statements

Conditional statements in ActionScript are a critical part of interactivity. They let you program a script based on any number of conditions. For example, in the morning, you say good day, or good morning to someone you meet. In doing so, you made a conditional choice.

ActionScript does the same thing. You can create an ActionScript that checks the time of day. If it’s before noon, Flash responds with a Good Morning message. If it’s from noon to 5, Flash says Good Afternoon, or from 5 till midnight, Flash says Good Evening. This type of condition is known as an if/else condition. If this happens, do this... else do that. Since a variable can be almost anything you can measure on a computer, and a conditional statement is made up of two or more variables, ActionScript can be taken to a point where it almost thinks for itself. The previous example could be expressed in flow charting the following way:

Using Conditional Statements

Typically, when you’re creating a conditional statement, you’re comparing one element against another using operators. The following operators are available to create conditional statements:

== Checks for equality between two values (is time of day equal to 5).

!= Checks for inequality between two values.

< Checks for less than (is value A less than value B).

> Checks for greater than (is value A greater than value B).

<= Checks for less than or equal to between two values.

>= Checks for greater than or equal to between two values.

&& Checks for a logical AND (if day == “Friday” && time > 5).

|| Checks for a logical OR (if day == “Saturday” || day == “Sunday”).

Using these operators to check between two or more values, you can create complex ActionScripts that react differently based on the available data. To create a dynamic field that checks the time, and responds with the appropriate answer, you would enter the following code:

   if (time > "0000 && time < 1200) {
     response = "Good Morning";
   } else if (time >1200 && time < 1700) {
     response = "Good Afternoon";
   }else if (time > 1700 && time < 2400);
     response = "Good Evening"
   }


Working with ActionScript Behaviors

Behaviors are time-savers because they give you sections of ActionScript 2.0 code (not supported in ActionScript 3.0) for common Flash tasks. Behaviors are a great way to introduce yourself to the wonderful world of ActionScripting without having to write all the code. For example, if you want to add a Play ActionScript to a button, you can do it using the Add button in the Behaviors panel, or you can write out the code on your own; see the example code below. Using Behaviors, as opposed to writing the code by hand, is not better, it’s simply faster. The more time you save doing common Action-Scripting tasks using Behaviors, the more time you will have for the creative process.

Using the Behaviors Panel

You use the Behaviors panel to apply the behavior to a triggering object, such as a button. You specify the event that triggers the behavior, such as releasing the mouse. Next select a target object, such as the movie clip instance, and then select settings for behavior parameters, such as a frame number or label, or a relative or absolute path. Flash comes with built-in behaviors, such as Load Graphic, Duplicate Movieclip, and GotoAndPlay At Frame Or Label. To add and configure a behavior, select a trigger object, and then step through the following general instructions (steps may vary depending on the behavior):

Using the Behaviors Panel Click the Window menu, and then click Behaviors.

Using the Behaviors Panel Click the Add (+) button, and then select a behavior from the menu.

Using the Behaviors Panel If necessary, select settings for the behavior parameters, and then click OK.

Using the Behaviors Panel Under Event, click On Release (the default event), and then select a mouse event from the menu.

Using the Behaviors Panel

Example Play ActionScript code

      on (release) {
           if(this.video_1._parent._currentframe == this.video_1.parent._totalframes){
               this.video_1parent.gotoAndPlay(1);
        } else {
            this.video_1._parent.play();
        }
      }


Using an ActionScript Behavior

You can use behaviors (ready-made scripts) to help you get started with ActionScript 2.0 (not supported in ActionScript 3.0). Here’s an example. The Start and Stop Dragging Movieclip Behaviors are a novel way to give Flash visitors the chance to interact with your site. The behaviors can be attached to objects on the screen. When the visitor clicks and drags an object, it is dragged along for the ride. For example, you could create a puzzle, and let the visitors assemble the puzzle. To begin the process, you will need an ActionScript 2.0 Flash document that contains one or more movie clips (for dragging).

Use the Start and Stop Dragging Behaviors

Use the Start and Stop Dragging Behaviors Create or open a Flash document (ActionScript 2.0), and then select the layer to contain the movie clip or clips.

Use the Start and Stop Dragging Behaviors

Use the Start and Stop Dragging Behaviors Drag the movie clips from the Library onto the Stage, and then enter a unique instance name for each movie clip.

Use the Start and Stop Dragging Behaviors Select a movie clip, click the Add (+) button in the Behaviors panel, point to Movieclip, and then click Start Dragging Movieclip.

Use the Start and Stop Dragging Behaviors Select the unique instance name for the movie clip.

Use the Start and Stop Dragging Behaviors Click OK.

Use the Start and Stop Dragging Behaviors Click the Event list arrow, and then change the event that triggers the behavior to On Press.

Use the Start and Stop Dragging Behaviors

Use the Start and Stop Dragging Behaviors With a selected movie clip, click the Add (+) button in the Behaviors panel, point to Movieclip, and then click Stop Dragging Movieclip.

Use the Start and Stop Dragging Behaviors Click OK.

Use the Start and Stop Dragging Behaviors Click the Event list arrow, and then change the event that triggers the behavior to On Release.

Use the Start and Stop Dragging Behaviors

Repeat steps 3 through 9 for all of the movie clips.

Use the Start and Stop Dragging Behaviors Click the Control menu, and then click Test Movie.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset