Chapter 25. Controlling Movie Clips

IN THIS CHAPTER

  • Understanding the MovieClip object

  • Working with properties of the MovieClip object

  • Creating Mouse Drag behaviors

  • Event models explained

  • Making sliders that dynamically change properties

In Chapter 19, "Building Timelines and Interactions," we established the key role that Movie Clips have within the Flash movie structure. By having a timeline that plays separately from other timelines, Movie Clips enable multiple events to occur—independently or as part of an interaction with other Movie Clips. In this chapter, we explore how to manipulate Movie Clips beyond navigation actions such as gotoAndPlay() or stop().

Note

In ActionScript 3.0, much of the functionality assigned to MovieClip instances in ActionScript 2.0 has shifted to other classes, the Sprite class, for example. In AS3, the MovieClip class should be used for elements that specifically need a timeline, such as an animation. In AS1 or AS2, the MovieClip class still remains a central element of production.

Movie Clips: The Object Overview

Since Flash 5, the implementation of ActionScript has resembled that of true object-oriented programming languages. Much like JavaScript, each element in a Flash movie has a data type. A data type is simply a category to which an element belongs. In the current version of ActionScript (including ActionScript 2.0), there are several data types available—boolean, number, string, object, function, and movieclip, among others.

Tip

If you want to see a list of all data types in ActionScript, open the Actions panel (make sure code hints are turned on), and type var a:. After you type the colon ( : ), you'll see a list of supported data types.

For our purposes, a Movie Clip instance is an object, and we'll refer to it as such throughout Part VII of this book. An object is any element in Flash that has changeable and accessible characteristics through ActionScript. Objects can be user-defined (you create and name them) or predefined by the programming language. The MovieClip class is a predefined class, meaning that all of its characteristics are already described in the ActionScript language.

A MovieClip object is the same Movie Clip instance you've seen in previous chapters. Any instance of a Movie Clip is a unique object in ActionScript. However, you haven't treated it like an object in your scripting. Before we can proceed with a discussion of Movie Clips as Flash movie assets, you need to understand what predefined characteristics are available in a MovieClip object. See Figure 25.1 for more information.

An overview of the MovieClip object

Figure 25.1. An overview of the MovieClip object

Movie Clip properties

Each Movie Clip instance has definable properties, or attributes, that control its appearance, size, and position. For example, you can move a Movie Clip instance to a new position on the stage by changing the value of its X or Y coordinate. This property in ActionScript is denoted as _x or _y, respectively. Some properties have read-only values, meaning these values can't be altered. One read-only property is _url, the value of which indicates the download location of the Movie Clip (or .swf file) such as http://www.yourserver.com/swf/background.swf. Figure 25.2 is a summary of the properties of the MovieClip object. For more information on each property, please refer to Table 25.1, "Flash Movie and Movie Clip Properties."

All properties are preceded by the underscore ( _ ) character. In Table 25.1, each property has an "R" (as in "read") and/or "W" (as in "write") designation. All properties can be read, which means that you can retrieve that property's current value. The values of some properties can also be changed through ActionScript. The table represents these properties with the "W" designation.

Note

In Flash Player 4 ActionScript, these properties were retrieved using the getProperty() action. Properties are altered using the setProperty() action. For Flash Player 5 or higher movies, you should avoid using these actions. Many free online Flash tutorials or samples at sites such as FlashKit.com will often be riddled with these deprecated actions.

Note

We don't review the more advanced properties of the MovieClip object in this chapter. For the most comprehensive coverage, refer to the MovieClip class coverage in the Flash 8 ActionScript Bible (Wiley).

Properties of a MovieClip object

Figure 25.2. Properties of a MovieClip object

Table 25.1. Flash Movie and Movie Clip Properties

Category

Property

Timeline

Flash 4

Flash 5+

Flash 8

Definition

MC = Movie Clip; R = Read property (cannot be modified); W = Write property (can be modified)

Position

_x

MC

RW

RW

RW

The horizontal distance between a Movie Clip's center point and the top-left corner of the stage upon which it resides. It increases as the clip moves to the right, and is measured in pixels.

  

Movie

RW

RW

RW

 
 

_y

MC

RW

RW

RW

The vertical distance between a Movie Clip's center point and the top-left corner of the stage upon which it resides. It increases as the clip moves downward, and is measured in pixels.

  

Movie

RW

RW

RW

 
 

_xmouse

MC

N/A

R

R

The horizontal distance (in pixels) between the zero point of a Movie Clip (or the Movie) and the current position of the mouse pointer.

  

Movie

 

R

R

 
 

_ymouse

MC

N/A

R

R

The vertical distance (in pixels) between the zero point of a Movie Clip (or the Movie) and the current position of the mouse pointer.

  

Movie

 

R

R

 
 

_rotation

MC

RW

RW

RW

The amount (in degrees) that a Movie Clip is rotated off plumb. It returns values set both by the Transform panel (or Transform tool) and by ActionScript.

  

Movie

RW

RW

RW

 
 

_xscale

MC

RW

RW

RW

The width of a Movie Clip instance (or Movie) as a percentage of the parent symbol's actual size.

  

Movie

RW

RW

RW

 

Size

_yscale

MC

RW

RW

RW

The height of a Movie Clip instance (or Movie) as a percentage of the parent symbol's actual size.

  

Movie

RW

RW

RW

 
 

_width

MC

R

RW

RW

The width (in pixels) of a Movie Clip or the main Movie Stage. It is determined not by the width of the canvas but by the width of the space occupied by elements on the Stage (meaning it can be less than or greater than the canvas width set in Movie Properties).

  

Movie

R

R

R

 
 

_height

MC

R

RW

RW

The height (in pixels) of a movie clip or the main movie. It is determined not by the height of the canvas but by the height of the space occupied by elements on the Stage.

  

Movie

R

R

R

 

Appearance

_alpha

MC

RW

RW

RW

The amount of transparency of a Movie Clip or Movie. It is measured as a percentage: 100 percent is completely opaque; 0 percent is completely transparent.

  

Movie

RW

RW

RW

 
 

_visible

MC

RW

RW

RW

A Boolean value that indicates whether a Movie Clip instance is shown or hidden. It is set to 1 (or true) to show; 0 (or false) to hide. Buttons in "hidden" movies are not active.

  

Movie

RW

RW

RW

 
 

filters

MC

N/A

N/A

RW

This property in Flash Player 8 or higher enables you to add visual effects to MovieClip objects. The filters property uses an array to describe which filters have been applied to the clip.

  

Movie

N/A

N/A

RW

 
 

transform

MC

N/A

RW

RW

This property in Flash Player 8 or higher enables you to control physical characteristics of a MovieClip object via transformation object. In Chapter 27, "Interacting with Movie Clips," we discuss the ColorTransform class, which can control the color properties of a MovieClip object.

  

Movie

N/A

N/A

RW

 

Internal Path

_name

MC

RW

RW

RW

This property returns or reassigns the Movie Clip instance's name (as listed in the Property inspector).

  

Movie

R

R

R

 
 

_target

MC

R

R

R

This property returns the exact string in Slash notation that you'd use to refer to the Movie Clip instance. To retrieve the dot syntax path, use eval(_target).

  

Movie

R

R

R

 
 

_droptarget

MC

R

R

R

This property returns the name (in Slash notation) of the last Movie Clip upon which a draggable Movie Clip was dropped. To retrieve the dots syntax path, use eval(_droptarget). For usage, see "Creating Draggable Movie Clips" in this chapter.

  

Movie

R

R

R

 
 

_lockroot

MC

RW

RW

RW

This property, only available to Flash Player 7 or higher -compatible movies, enables you to control how a _root reference is interpreted. If the _lockroot property of a MovieClip object is set to true, then any child assets (nested MovieClip objects) will see the parent MovieClip object as _root. For example, if you load an .swf file into a MovieClip object, any _root target in the loaded .swf will point to the MovieClip object.

  

Movie

RW

RW

RW

 
 

_parent

MC

N/A

R

R

This property returns a reference to the parent timeline of the current MovieClip object. For example, if an instance named bird_1 exists within another instance named flock_mc, then bird_1._parent refers to the flock_mc instance.

  

Movie

N/A

R

R

* _parent will return only a valid reference from the Main Timeline if the Flash movie is loaded into a MovieClip instance of another Flash movie.

External Path

_url

MC

R

R

R

This property returns the complete path to the Flash movie (.swf) in which the action is executed, including the name of the Flash movie file (.swf) itself. It can be used to prevent a movie from being viewed if it is not on a particular server.

  

Movie

R

R

R

 

Timeline

_currentframe

MC

R

R

R

This property returns the number of the current frame (for example, the frame on which the Playhead currently resides) of the Movie or a Movie Clip instance.

  

Movie

R

R

R

 
 

_totalframes

MC

R

R

R

This property returns the number of total frames in a Movie or Movie Clip instance's timeline.

  

Movie

R

R

R

 
 

_framesloaded

MC

R

R

R

This property returns the number of frames that have downloaded over the network.

  

Movie

R

R

R

 

Global

_quality

Movie

N/A

RW

RW

The visual quality of the movie. The value is a string equal to: "LOW" (no antialiasing, no bitmap smoothing), "MEDIUM" (antialiasing on a 2 × 2 grid, no bitmap smoothing), "HIGH" (antialiasing on a 4 × 4 grid, bitmap smoothing on static frames), "BEST" (antialiasing on a 4 × 4 grid, bitmap smoothing on all frames).

 

_focusrect

Movie

RW

RW

RW

A Boolean value that indicates whether a yellow rectangle is shown around buttons when accessed via the Tab key. The default is to show. When set to 0, the Up state of the button is shown instead of the yellow rectangle.

 

_soundbuftime

Movie

RW

RW

RW

The number of seconds a sound should preload before it begins playing. The default is five seconds.

Note

Use the propInspector Movie Clip in the Library of the property_inspector.fla file, located in the ch25 folder of this book's CD-ROM, to see the values of Movie Clip or Movie properties.

Movie Clip methods

Although the name might sound intimidating, don't be scared. Methods are simply actions that are attached to objects. As you now know, Movie Clips qualify as objects in ActionScript. A method looks like a regular action, except it doesn't (and, in most cases, can't) operate without a dot syntax reference to a target or an object:

Action: gotoAndPlay("start");

becomes

Method: myMovieClip.gotoAndPlay("start");

As actions, interactive commands are executed from the timeline on which they are written. As methods, interactive commands are tied to specific (or dynamic) targets. Figure 25.3 lists many of the methods and Table 25.2 reviews them in more detail. Some methods can be used with MovieClip instances and with the entire Flash movie (_root, _level0, and so on), while others can only be used with MovieClip instances. The "Flash 4" column in Table 25.2 indicates if the method (when used as an action) is compatible in Flash Player 4. Some commands need to be written in dot syntax, as a method (designated as "M" in the table) of a timeline or MovieClip object. Other commands can be used as actions (designated as "A" in the table), meaning that the MovieClip object name need not precede the command.

Note

Figure 25.3 and Table 25.2 do not contain all methods of the MovieClip class. For comprehensive descriptions and usage of the methods, refer to the Flash 8 ActionScript Bible (Wiley).

Common methods of the MovieClip object

Figure 25.3. Common methods of the MovieClip object

Table 25.2. Common Movie and Movie Clip Methods

Category

Method

Flash 4

Definition

Usage

M = Method; A = Action

Position

hitTest

No

Determines if a MovieClip object overlaps with the boundaries of another MovieClip object, or if an X-Y coordinate intersects with a MovieClip instance. For more information on this method, see Chapter 27, "Interacting with Movie Clips."

timeline.hitTest(MovieClip object);

OR

timeline.hitTest(x coordinate, y coordinate, shapeFlag);

 

M

  

myMC.hitTest(myOther_mc);

    

myMC.hitTest(_root._xmouse, _root._ymouse, true);

 

startDrag

Yes

Enables the user to move a Movie Clip instance on the Stage. The Movie Clip moves (or drags) in tandem with the movements of the mouse. You can specify whether the mouse pointer locks to the center of the Movie Clip instance and if the drag area is constrained to a range of X and Y coordinates (in the parent symbol or timeline space). Constraining the drag area is useful for slider controls.

timeline.startDrag(lock, min X, min Y, max X, max Y);

 

M, A

  

myMC.startDrag(false, 200,0,200,200);

 

stopDrag

Yes

Stops any startDrag action currently in progress. No target needs to be specified with this action.

timeline.stopDrag();

 

M, A

  

myMC.stopDrag();

Playback

play

Yes

Starts playback from the current position of the Playhead on a specified timeline.

timeline.play();

 

M, A

  

_root.play(); // plays the Main Timeline

    

_root.myMC.play(); // plays myMC

 

stop

Yes

Stops playback on a specified timeline.

timeline.stop();

 

M, A

  

_root.stop(); // stops the Main Timeline

    

_root.myMC.stop(); // stops myMC

 

gotoAndPlay

Yes

Jumps the Playhead of a specified timeline to a label, frame number, or expression, and starts playing from there.

timeline.gotoAndPlay(position);

 

M, A

  

_root.myMC.gotoAndPlay("start");

    

// plays from the "start" label of the myMC timeline

 

gotoAndStop

Yes

Jumps the Playhead of a specified timeline to a label, frame number, or expression, and stops playback.

timeline.gotoAndStop(position);

 

M, A

  

_root.myMC.gotoAndStop("mute");

    

// stops playback on the "mute" label of myMC

 

nextFrame

Yes

Moves the Playhead of the specified timeline to the next frame.

timeline.nextFrame();

 

M, A

  

_root.myMC.nextFrame();

 

prevFrame

Yes

Moves the Playhead of the specified timeline to the previous frame.

timeline.prevFrame();

 

M, A

  

_root.myMC.prevFrame();

Internal Assets

createEmptyMovieClip

No

Makes a blank (empty) Movie Clip instance on the Stage (or nested in another Movie Clip instance). The new instance is placed directly above the parent instance, at a specified depth. Higher depth numbers appear above lower depth numbers (for example, a Movie Clip at depth 2 is stacked above a Movie Clip at depth 1).

 
   

This method works in Flash Player 6 or higher.

timeline.createEmptyMovieClip(new name*, depth);

 

M

  

_root.createEmptyMovieClip("myMC", 1);

    

myMC._x = 50;

    

*You should only specify an instance name for the new MovieClip object—not a new path. You can only create new instances relative to the instance invoking the method.

 

duplicateMovieClip

Yes

Makes a copy of an existing Movie Clip instance on the Stage (or nested in another Movie Clip). The new copy is placed directly above the parent instance, at a specified depth. Higher depth numbers appear above lower depth numbers (for example, a Movie Clip at depth 2 is stacked above a Movie Clip at depth 1).

timeline.duplicateMovieClip(new name*, depth);

 

M, A

  

myMC.duplicateMovieClip("myMC_2", 20);

    

myMC_2._x = 200;

    

*See note for the createEmptyMovieClip() method.

 

removeMovieClip

Yes

Deletes a previously duplicated Movie Clip instance. When used as a method, you do not need to specify a target. You cannot remove a Movie Clip instance that is manually inserted on any timeline frame from the Library.

timeline.removeMovieClip();

 

M, A

  

myMC_2.removeMovieClip();

 

attachMovie

No

Places an instance of a Movie Clip symbol from the Library into the specified timeline. Each attached instance requires a unique name and depth. Attached Movie Clip instances can be deleted with removeMovieClip.

timeline.attachMovie(ID*, new name, depth);

 

M

  

_root.attachMovie("eye", "eye_1", 1);

    

*You need to specify a unique identifier to linked Movie Clip symbols in the Library, using the Linkage Properties.

 

getDepth

No

Returns the current depth of a duplicated (or attached) MovieClip object.

 
   

This method only works in Flash 6 movies played in Flash Player 6.

timeline.getDepth();

 

M

  

_root.attachMovie("eye", "eye_1", 1);

    

trace(eye_1.getDepth());

    

*If you attempt to retrieve the depth of a Movie Clip instance that you manually placed on the Stage, then ActionScript will return −16383 as the value of getDepth().

 

swapDepths

No

Switches the depth placement of two duplicated or attached Movie Clips. This method is useful for placing one Movie Clip instance in front of (or behind) another instance.

timeline.swapDepths(depth);

 

M

  

timeline.swapDepths(target);

    

eye_1.swapDepths(10); // depth

    

eye_1.swapDepths(eye_2); // target

 

getNextHighestDepth

No

Determines if any objects currently exist within depth slots of the current MovieClip object, and returns a depth number one higher than an occupied slot. For example, if you duplicated a MovieClip object to a depth count of 2, this method would return 3. You can use this method in conjunction with any of the Movie Clip methods that require a depth parameter.

 
   

This method works only when issued from a Flash Player 7 or higher movie.

timeline.getNextHighestDepth();

 

M

  

var nextSlot = myMC.getNextHighestDepth();

 

getInstanceAtDepth

No

Returns the name of an object occupying the specified depth slot. If no object exists at the slot, undefined is returned.

 
   

This method works only when issued from a Flash Player 7 or higher movie.

timeline.getInstanceAtDepth(depthSlot);

 

M

  

var isOccupied = myMC.getInstanceAtDepth(1);

 

createTextField

No

Adds a new TextField object (that is, a dynamic or input text field) to the MovieClip object. This method enables you to add new text fields to your movie at runtime.

 
   

This method works only when issued from a Flash Player 6 or higher movie.

timeline.createTextField(name, depth, x position, y position, width, height);

 

M

  

myMC.createTextField("display_txt", 1, 10, 10, 300, 50);

 

setMask

No

Assigns a MovieClip object to be used as the mask for another MovieClip object.

 
   

This method works only when issued from a Flash Player 6 or higher movie.

timeline.setMask(instanceName);

 

M

  

myMC.setMask(clip_mc);

External Assets

loadMovie

Yes

Loads an external movie file (.swf) or image file into the main movie. As one of the most powerful features of Flash, this method enables you to break up your Flash movie into several smaller components, and load them as needed. This method can load movie files (.swf) or standard JPEG image files (.jpg) into Flash Player 6 or higher movies. Flash Player 8 or higher movies can also load GIF, PNG, and progressive JPEG images into Movie Clip targets.

timeline.loadMovie(path, send variables*);

 

M, A

  

myMC.loadMovie("menu.swf");

    

OR

    

myMC.loadMovie("image.jpg");

    

*You can also send Flash variables to the newly loaded .swf file with an optional "GET" or "POST" parameter. We discuss this in Chapter 24, "Knowing the Nuts and Bolts of Code."

 

unloadMovie

Yes

Removes an externally loaded movie file (.swf) or image file from the main movie. This method enables you to dump movie assets when they are no longer needed. Use this method for assets loaded into Movie Clip targets.

timeline.unloadMovie();

 

M, A

  

myMC.unloadMovie();

 

loadVariables

Yes

Loads external text-based data into the movie. This method enables you to access data (in the form of variable name/value pairs) from server-side scripts or text files, and place it in a Movie Clip target.

timeline.loadVariables(path, send variables*);

 

M, A

  

myMC.loadVariables("info.txt");

    

*See note in loadMovie. We discuss loadVariables() and the LoadVars object in Chapter 29, "Sending Data In and Out of Flash."

 

getBytesLoaded

No

Returns the number of bytes that have streamed into the Flash Player for a specified Movie Clip (or movie).

timeline.getBytesLoaded();

 

M

  

loadBytes = myMC.getBytesLoaded();

 

getBytesTotal

No

Returns the total file size (in bytes) for a loading movie or Movie Clip. Combined with getBytesLoaded(), you can use this method to calculate the movie's loaded percentage.

timeline.getBytesTotal();

 

M

  

totalBytes = myMC.getBytesTotal();

    

loadBytes = myMC.getBytesLoaded();

    

newPercent = (loadBytes/totalBytes)*100;

 

getSWFVersion

No

Returns the version of the Flash movie as a number. For example, if you create a Flash movie (.swf) to be Flash Player 4–compatible, you can check the version number of that .swf from a Flash Player 7–compatible movie file (.swf).

 
   

This method can only be invoked from Flash movies created for Flash Player 7 or higher.

timeline.getSWFVersion();

 

M

  

myMC.getSWFVersion();

onClipEvent: The Flash Player 5 Movie Clip handler

In Flash Player 5, the onClipEvent handler was added to the ActionScript language. In Flash Player 4 or earlier, the only event handlers were keyframes and Button instances. In Flash Player 5 or higher movies, you can add actions to the wrapper of a Movie Clip instance—meaning that these actions are not added to keyframes on the Movie Clip's timeline. Nine events can be used with the onClipEvent handler. Refer to Table 25.3 for a summary of these events.

Here's how you create a simple example of onClipEvent() in action:

  1. Create a new Flash file (ActionScript 2.0), using File

    onClipEvent: The Flash Player 5 Movie Clip handler
  2. Draw any artwork you wish, and make the artwork a Movie Clip symbol.

  3. Select the Movie Clip instance on the Stage. In the Property inspector, name the instance tracker.

  4. With the tracker instance selected on the Stage, open the Actions panel (F9, or Option+F9). Type the following code into the Script pane:

    onClipEvent (mouseMove){
      this._x = _root._xmouse;
      this._y = _root._ymouse;
      updateAfterEvent();
    }

    This code uses onClipEvent() to track the position of the user's mouse, and apply that position to the MovieClip object—effectively moving the MovieClip object with the mouse pointer. The code is executed every time the user's mouse moves. The updateAfterEvent() action will tell the Flash Player to refresh the video display each time a mouse move is detected, resulting in a smoother movement of the object.

  5. Save your Flash document as tracker_oce.fla, and test it (Ctrl+Enter or

    onClipEvent: The Flash Player 5 Movie Clip handler

Note

You can find a completed version of the file tracker_oce.fla in the ch25 folder of this book's CD-ROM.

Event methods: The more flexible Movie Clip handler

In Flash Player 6 and higher, event handlers for MovieClip objects can be written and executed from any other event handler. This means that you can code the same event handlers used for onClipEvent() in keyframe or Button instance actions. While this may not seem like a monumental leap forward, this new event model enables you to create event handlers that are not directly attached to physical instances of a Movie Clip in the authoring environment. For a summary of common event methods, see Table 25.3.

Note

It is beyond the scope of this book to discuss all of the event methods available in ActionScript 1.0 and 2.0. Please refer to the Flash 8 ActionScript Bible (Wiley) for more information.

To get a better idea of how this event model works, create this simple example:

  1. Create a new Flash file (ActionScript 2.0).

  2. Draw some artwork, and make it a Movie Clip symbol.

  3. Select the new instance on the Stage. Name the instance tracker in the Property inspector.

  4. Create a new layer on the Main Timeline (that is, Scene 1). Name the layer actions.

  5. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on Mac). Type the following code into the Script pane:

    var tracker:MovieClip;
       tracker.onMouseMove = function (){
       this._x = _root._xmouse;
       this._y = _root._ymouse;
       updateAfterEvent();
    };

    This code adds an onMouseMove() method to the tracker instance. Each time the user's mouse moves, the function written for the method will execute. We discuss functions in the next chapter.

  6. Save your Flash document as tracker_eventmodel.fla, and test it (Ctrl+Enter or

    Event methods: The more flexible Movie Clip handler

Note

You can find the completed document, tracker_eventmodel.fla, in the ch25 folder of this book's CD-ROM. You will also find another document, tracker_eventmodel_adv.fla, which uses multiple event handlers.

You can continue to add more event methods to the tracker instance, in order for the instance to respond to mouse clicks, time elapsing, and so on.

Warning

This event model for Flash movies works in Flash Player 6 or higher. If you need to use events with Movie Clips that are compatible with Flash Player 5, then use onClipEvent() handlers.

Table 25.3. Common Flash Player 5 and Higher Event Handlers

Category

onClipEvent (FP5+)

Event Handler (FP6+)

Definition

Usage

Playback

load

onLoad

This event is triggered when (A) a Movie Clip instance first appears on the Stage; (B) a new instance is added with attachMovie or duplicateMovieClip; or (C) an external Flash movie file (.swf) is loaded into a Movie Clip target.

Note: The onLoad method does not function properly on individual instances. When a Flash movie file (.swf) loads into a level or a Movie Clip target, any existing methods will be overwritten, including onLoad. See the Usage example to see how onLoad can be used. The onLoad method, however, is useful for setting parameters for components that are added via ActionScript.

onClipEvent(load){
 trace( _name + " has
 loaded.");
 }

OR

MovieClip.prototype.
onLoad = function(){
 trace("A movie or Movie
Clip has loaded.");
};
 

unload

onUnload

This event occurs when (A) a Movie Clip instance exits the Stage (just after the last frame has played on the Main Timeline), or (B) an external Flash movie file (.swf) is unloaded from a Movie Clip target. Actions within this handler type will be executed before any actions in the keyframe immediately after the Movie Clip's departure keyframe.

onClipEvent(unload){
 trace( _name + " has
unloaded.");
}

OR

mcHolder.onUnload =
function(){
 trace(this._name + " has
unloaded.");
};
 

enterFrame

onEnterFrame

This event executes when each frame on a Movie Clip instance's timeline is played. The actions within this event handler will be processed after any actions that exist on the keyframes of the Movie Clip Timeline. Note that enterFrame events will execute repeatedly (at the same rate as the movie's frame rate), regardless of whether any timelines within the movie are actually playing frames.

onClipEvent(enterFrame){
 trace( _name + " is
playing.");
}

OR

mcHolder.onEnterFrame =
 function(){
 trace(_name + " is
playing.");
};

User Input

mouseMove

onMouseMove

This event is triggered each time the mouse moves anywhere on the Stage. All Movie Clip instances with this event handler defined receive this event. Combined with the hitTest() method, this event can be used to detect mouse movements over Movie Clip instances.

onClipEvent(mouseMove){
 var myX = _root._xmouse;
 var myY = _root._ymouse;
 if(this.hitTest(myX, myY,
true) == true){
 trace("Mouse move over
MC.");
 }
}

OR

mcHolder.onMouseMove =
function(){
 var myX:Number  =
 _root._xmouse;
 var myY:Number=
 _root._ymouse;
  if(this.hitTest(myX, myY,
 true)){
  trace("Mouse move over " +
 this._name);
  }
  updateAfterEvent();
  };
 

mouseDown

onMouseDown

This event occurs each time the left mouse button is pressed (or down) anywhere on the Stage. All Movie Clip instances with this event handler receive this event.

onClipEvent(mouseDown){
 myX = _root._xmouse;
 myY = _root._ymouse;
 if(this.hitTest(myX, myY,
true)){
 trace("Mouse press on
MC.");
 }
}

OR

mcHolder.onMouseDown =
function(){
var myX:Number =
_root._xmouse;
var myY:Number =
_root._ymouse;
 if(this.hitTest(myX, myY,
true)){
 trace("Mouse press on " +
this._name);
 }
};
 

mouseUp

onMouseUp

This event is triggered each time the left mouse button is released (when the user lets up on the mouse button). All Movie Clip instances with this handler receive this event.

onClipEvent(mouseUp){
 myX = _root._xmouse;
 myY = _root._ymouse;
 if(this.hitTest(myX, myY,
true)){
 trace("Mouse release on
MC.");
 }
}

OR

mcHolder.onMouseUp=
function(){
var myX:Number =
_root._xmouse;
var myY:Number =
_root._ymouse;
if(this.hitTest(myX, myY,
true)){
 trace("Mouse release on "
+ this._name);
 }
};
 

keyDown

onKeyDown

This event occurs when the user presses a key. Combined with the Key.getCode method, you can use this event handler to detect unique key presses.

Note: It's better to use Key.addListener() with a listener object to detect key down events.

onClipEvent(keyDown){
 newKey = Key.getCode();
 myKey = Key.UP;
 if(newKey == myKey){
 trace("UP arrow is
pressed.");
 }
}
 

keyUp

onKeyUp

This event happens when the user releases a key (when the finger leaves the key). It provides the same functionality as the keyDown event.

Note: It's preferable to use Key.addListener() with a listener object to detect key down events. We discuss this advanced use of the Key class in the Flash ActionScript Bible series by Robert Reinhardt and Joey Lott (Wiley).

onClipEvent(keyUp){
 newKey = Key.getCode();
 myKey = Key.LEFT;
 if(newKey == myKey){
 trace("LEFT arrow
released.");
 }
}

External Input

data

onData

This event is triggered when (A) the loadMovie action retrieves an external Flash movie file (.swf) and puts it in a Movie Clip target, or (B) the data from a file or script with the loadVariables action (targeted at a Movie Clip instance) is finished loading.

Note: If you're building Flash Player 6 or higher movies, use the LoadVars class to load URL-encoded variables into a Flash movie. Learn more about the LoadVars class in Chapter 30, "Sending Data In and Out of Flash."

onClipEvent(data){
trace("New data
received.");
}

OR

mcHolder.onData =
function(){
trace("New data
received.");
}

Other classes and functions that use the MovieClip object

You can use Movie Clips with other ActionScript classes to control appearances and sounds, and to manipulate data.

ColorTransform class

This class can control the color effects of the targeted Movie Clip.

Tip

Flash Player 8 introduced a new MovieClip class property, transform. The transform property controls color transformations applied to a MovieClip instance. For more information about this new feature, read Chapter 27, "Interacting with Movie Clips."

Sound class

With this class, you can create virtual sound instances on a MovieClip instance and target them for later use.

Mouse class

This class controls the appearance of the mouse pointer within the Flash movie. After the Mouse object is hidden, you can attach a MovieClip object to the X and Y coordinates of the mouse pointer.

PrintJob API

Flash MX 2004 and Flash Player 7 introduced the ActionScript class, PrintJob. PrintJob objects enable you to send MovieClip instances—as pages to a user's printer. The PrintJob class offers you more control over printing than previous versions of the Flash Player. You learn more about the PrintJob API in Chapter 27, "Interacting with Movie Clips."

Note

You can still use the print() function for Flash Player 6 or earlier movies. This function prints a frame (or series of frames) in the targeted timeline. Each frame prints to one piece of paper. Use this function to print high-quality artwork. Note that alpha and color effects applied to MovieClip objects do not print reliably with this method—use the printAsBitmap() function instead.

with() action

This action enables you to avoid needless replication of object references and paths. By specifying a target for the with() action, you can omit the path from nested actions. We demonstrate the with() action in the next section.

tellTarget() action

This Flash Player 4–compatible action can direct actions to a specific Movie Clip Timeline. To be compatible with Flash Player 4, you need to use slash syntax for the target path. We strongly discourage you from using tellTarget() actions if you are designing Flash Player 5 or higher movies.

Working with Movie Clip Properties

Now that you have a sense of what a Movie Clip can do (or be told to do), it's time for you to get some practical experience with the Movie Clip properties. In this section, we show you how to access Movie Clip appearance properties that control position, scale, and rotation.

Note

The following exercises use Button symbols from the prebuilt Common Libraries that ship with Flash CS3. To access buttons from the Common Libraries, use Window

Working with Movie Clip Properties

Positioning Movie Clips

You can change the location of MovieClip instances on the fly with position properties such as _x and _y. How is this useful? If you want to create multiple MovieClip instances that move randomly (or predictably) across the Stage, you can save yourself the trouble of manually tweening them by writing a few lines of ActionScript code on the object instance. Here are the steps to take:

  1. Create a new Flash file (ActionScript 2.0) by choosing File

    Positioning Movie Clips
  2. Rename Layer 1 to circle.

  3. On frame 1 of the circle layer, draw a simple shape such as a circle. Select the shape and press the F8 key to convert it into a symbol. Choose the Movie Clip behavior in the Convert to Symbol dialog box, and give the new Movie Clip symbol a unique name such as circleClip.

  4. Select the instance on the stage of the Main Timeline, and in the Property inspector, name the instance circle.

  5. Create a new layer on the Main Timeline (that is, Scene 1), and name the layer actions.

  6. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on Mac). Type the following code into the Script pane:

    var circle:MovieClip;
    
    circle.onEnterFrame = function(){
         this._x += 5;
    };
  7. Save your document as movieclip_x.fla, and test the movie (Ctrl+Enter or

    Positioning Movie Clips

Note

You can find the movieclip_x.fla in the ch25 folder of this book's CD-ROM.

How does this code work? In Step 4, you specified that the onEnterFrame() event method should be assigned to the Movie Clip instance circle. Regardless of the number of frames on any playing timeline, the enterFrame event is triggered continuously. Therefore, any actions nested within the handler will be executed repeatedly.

Your nest contains one action: this._x += 5. On the left side of the action, this refers to the object instance to which this handler and code has been applied. In your case, this refers to your circle Movie Clip instance. Immediately after this is the property for the X position, _x. By adding the property _x to the object this, Flash knows that you want to change the value of this property.

On the right side of the action are the operators += and the value 5. By combining the + and = operators, you've created a shortcut to adding the value of 5 to the current X position of the circle Movie Clip instance. Each time the enterFrame event occurs, the circle object moves 5 pixels to the right.

To show how quickly you can replicate this action on multiple Movie Clips, select the circle instance on the Stage, and duplicate it (Ctrl+D or

Positioning Movie Clips
circle_2.onEnterFrame = function():Void{
     this._x += 10;
};
circle_3.onEnterFrame = circle_2.onEnterFrame;

When you test your movie, each instance moves independently across the Stage. Notice that the onEnterFrame() handler for the circle_3 instance borrows the onEnterFrame() handler from circle_2. Once a method has been defined for one object, you can reuse it with other objects' methods.

Tip

To move the instance diagonally across the Stage, add the action this._y += 5 to the onEnterFrame() handler. This moves the instance down 5 pixels each time the handler is processed. Also, we'll show you how to consolidate duplicated actions in Chapter 26, "Using Functions and Arrays."

Scaling Movie Clips

In the last example, you learned how to access the _x and _y properties of the MovieClip object. The next example shows you how to use a Button symbol to enlarge or reduce the size of a Movie Clip on the Stage:

  1. Create a new Flash file (ActionScript 2.0).

  2. Draw a shape (or multiple shapes), select the shape(s), and press the F8 key to convert the artwork into a symbol. Give the Movie Clip symbol a distinct name to identify it in the Library.

  3. Select the instance of the Movie Clip on the Stage, and open the Property inspector. Give the Movie Clip a unique name. In this example, we've named the instance circle.

  4. From the Button library, drag an instance of a button onto the Stage. Name the instance incrButton (short for increase button) in the Property inspector.

  5. Now create the ActionScript code that will enlarge the circle Movie Clip instance. Create a new layer named actions. Select frame 1 on this layer, and open the Actions panel. Type the following code into the Script pane:

    var incrButton:Button;
    var circle:MovieClip;
    
    incrButton.onRelease = function():Void{
      with (circle){
        _xscale += 10;
        _yscale += 10;
      }
    };

    This code uses the with() action to target the circle instance with a nested group of actions. In this case, you've increased the values of the _xscale and _yscale properties by 10 percent. With each release event on the Button symbol instance, the scale properties of the circle instance will be changed.

  6. Save your document as movieclip_scale.fla, and test the movie (Ctrl+Enter or

    Scaling Movie Clips
  7. Duplicate the Button instance (Ctrl+D or

    Scaling Movie Clips
    var decrButton:Button;
    
    decrButton.onRelease = function():Void {
      with (circle){
        _xscale -= 10;
        _yscale -= 10;
      }
    };

    By changing the += operator to -=, each click on this Button instance reduces (shrinks) the circle instance by 10 percent.

  8. Resave your Flash file and test the movie again. Make sure that each Button instance behaves appropriately. If one doesn't work (or works in an unexpected manner), go back to the Flash document and check the code on both Button instances.

Note

You can find the movieclip_scale.fla document in the ch25 folder of this book's CD-ROM.

Warning

In this simple exercise, we haven't placed any limits on the how much the Movie Clip can be reduced or enlarged. If you click the reduce button enough times, the Movie Clip instance will actually flip vertically and start enlarging again. We look at creating conditions and logic for Movie Clips in Chapter 27, "Interacting with Movie Clips."

Rotating Movie Clips

Let's move along to the rotation property, _rotation, which is used to control the angle at which your Movie Clip is shown. In this sample, you'll use the same Flash document that you created in the previous section.

Note

If you drew a perfect circle in past exercises for the MovieClip object, then you will want to edit your Movie Clip symbol to include some additional artwork that provides an indication of orientation and rotation. If you try to rotate a perfect circle, you won't see any visual difference on the Stage. Because the value of the _rotation property is determined from the center point of the Movie Clip, you can also move the contents of the Movie Clip (in Edit mode) off-center to see updates in the _rotation value.

  1. Select frame 1 of the actions layer, and open the Actions panel. Change the incrButton instance's ActionScript code to:

    incrButton.onRelease = function():Void {
       circle._rotation += 10;
    };
  2. Now, change the decrButton instance's ActionScript code in the Actions panel to:

    decrButton.onRelease = function():Void {
       circle._rotation -= 10;
    };
  3. Save your document as movieclip_rotation.fla, and test the movie. Each button should rotate the circle Movie Clip instance accordingly.

Note

You can find the movieclip_rotation.fla document in the ch25 folder of this book's CD-ROM.

At this point, you should have a general knowledge of how to access a Movie Clip's properties. Repeat these examples using other properties that can be modified, such as _width and _height. Try combining all the properties into one Button instance handler, or one event method or onClipEvent() handler.

Creating Draggable Movie Clips

Flash Player 4 introduced the drag-and-drop feature, which enables the user to pick up objects with the mouse pointer and move them around the movie Stage. Flash Player 5 added some other ways to use drag-and-drop with the onClipEvent() Movie Clip handler. As we briefly discussed, Flash Player 6 and higher ActionScript can use a different event model for MovieClip objects. Drag-and-drop in Flash is based entirely on Movie Clips. The only objects that can be moved with the mouse are Movie Clip instances. So, if you want a drawing of a triangle to be moveable by the user, you have to first put that triangle into a Movie Clip, and then place a named instance of that clip onto the Stage. Flash's drag-and-drop support is fairly broad, but more-complex drag-and-drop behaviors require some ActionScript knowledge.

Drag-and-drop basics

In mouse-based computer interfaces, the most common form of drag-and-drop goes like this: A user points to an element with the mouse pointer, clicks the element to begin moving it, and then releases the mouse button to stop moving it. One method of adding drag-and-drop functionality is the use of a button handler with a MovieClip instance. A startDrag() action is added to an onPress() handler for that MovieClip instance. Let's try out this technique.

  1. Start a new Flash file (ActionScript 2.0). Rename Layer 1 to dragger.

  2. Create a circle with the Oval tool. Select the artwork and press F8. In the Convert to Symbol dialog box, select the MovieClip type. Name the symbol dragClip. Make sure the registration point is set to the center of the clip.

  3. With the new Movie Clip instance selected, open the Property inspector. Give the instance the name dragger.

  4. On the Main Timeline (that is, Scene 1), create a new layer named actions and place this layer at the top of the layer stack. Select the first frame of the actions layer, and open the Actions panel (F9, or Option+F9 on Mac). Type the following code into the Script pane:

    var dragger:MovieClip;
    dragger.onPress = function():Void {
      this.startDrag();
    };

    Even though this startDrag() method will be applied to the same Movie Clip (this), a startDrag() method can target any Movie Clip from any button, or from any keyframe.

  5. At this point, your MovieClip instance button, when clicked, causes the instance to start following the mouse pointer. Now you have to tell the Movie Clip to stop following the pointer when the mouse button is released. After the last curly brace ( } ) highlighted in the actions list of the Script pane, type the following code:

    dragger.onRelease = dragger.onReleaseOutside = function():Void{
      this.stopDrag();
    };

    Tip

    You should add an onReleaseOutside() handler to capture all release-based events, just in case the mouse is outside of the hit area of the button when the mouse button is released.

  6. Save your Flash document as movieclip_button_drag.fla. Test your movie with Control

    Drag-and-drop basics

Note

You can find the movieclip_button_drag.fla document in the ch25 folder of this book's CD-ROM.

Did it work? Great! Now we can tell you about the other basic settings for the startDrag() action. Next, you'll look at additional features of the startDrag() action. You may want to select an existing startDrag() action in the Script pane of the Actions panel and click the Reference icon in the panel's toolbar to more clearly see these options.

Lock mouse to center

This setting, which is the first option specified in the parentheses of the startDrag() method, controls how the Movie Clip instance will position itself relative to the position of the mouse pointer. There are two values for this option: true or false. When set to true, this option makes the dragged Movie Clip instance center itself under the mouse pointer for the duration of the drag movement. If the dragged Movie Clip instance is not already under the mouse pointer when the startDrag() action occurs, the instance will automatically be moved under the pointer, providing that the pointer is not outside the region defined by Constrain to Rectangle (discussed in the next section). The following code will "snap" the center of the Movie Clip instance dragger to the mouse pointer:

dragger.startDrag(true);

When this option is set to false, the Movie Clip instance moves with the mouse pointer from the point at which it was clicked. For example, if you click the draggable object on its left edge, then that's where the object will "snap" the mouse pointer:

dragger.startDrag(false);

Constrain to rectangle

In order to specify the limits of the rectangular region within which a draggable Movie Clip instance can be dragged, you can add parameters to the startDrag() method. First, determine the pixel locations of the four corners of the rectangle. The pixel coordinates are set relative to the top-left corner of the Stage upon which the draggable Movie Clip instance resides. For example, the following code would constrain the draggable Movie Clip instance named dragger to a 300-pixel square region in the top-left corner of the Main Timeline's Stage:

dragger.startDrag(false, 0, 0, 300, 300);

Note

If the draggable Movie Clip instance is located outside of the defined drag region when the startDrag() action occurs, the instance is automatically moved into the closest portion of the drag region.

Detecting the drop position: Using _droptarget

In the "Drag-and-drop basics" section, we showed you how to make Movie Clip instances that the user can move around. But what if you want to force the user to move a Movie Clip object into a certain location before you let her drop it? For instance, consider a child's shape-matching game in which a small circle, square, and triangle should be dragged onto corresponding larger shapes. If the child drops the small circle onto the large square or large triangle, the circle returns to its original location. If, on the other hand, the child drops the small circle onto the large circle, the small circle should stay where it is dropped, and the child should receive a "Correct!" message. That kind of game is quite possible in Flash, but it requires some understanding of Movie Clip properties. Here's how it works—you'll use the circle as an example.

  1. Create a new Flash file (ActionScript 2.0), and save it as movieclip_droptarget.fla.

  2. Rename Layer 1 to circle.

  3. On frame 1 of the circle layer, use the Oval tool to draw a circle that is 100 × 100 pixels. Convert the artwork to a Movie Clip symbol named circleClip, and name the instance circle. Scale the artwork to 25 percent in the Transform panel. Position this instance along the bottom left of the Stage, as shown in Figure 25.4.

    The circle instance

    Figure 25.4. The circle instance

  4. Copy the circle instance by selecting it on the Stage and choosing Edit

    The circle instance
  5. Create a new layer, and name the layer circleBig. Place the layer below the circle layer.

  6. On frame 1 of the circleBig layer, choose Edit

    The circle instance
    The circleBig instance

    Figure 25.5. The circleBig instance

  7. Create a new Movie Clip symbol from scratch by choosing Insert

    The circleBig instance
  8. Go back to the Main Timeline (that is, Scene 1), and place an instance of statusClip along the bottom of the Stage, centered. With the instance selected, open the Property inspector and name the instance statusMsg.

    The statusClip symbol timeline with a Blur filter tween

    Figure 25.6. The statusClip symbol timeline with a Blur filter tween

  9. Now, you will make the circle instance draggable by adding some frame actions. On the Main Timeline, create a new layer named actions and place this layer above the other layers. Select frame 1 of the actions layer, and in the Actions panel type the following code into the Script pane:

    var circle:MovieClip;
    var circleBig:MovieClip;
    var statusMsg:MovieClip;
    
       circle.onPress = function(){
      this.startDrag();
    };

    Here, the onPress() method of the MovieClip object is used to assign a button press behavior to the instance. In this code, you tell the circle instance to start dragging when it is clicked on the Stage. Note that as soon as a Movie Clip instance has a button event assigned to it, the mouse pointer will switch to a finger icon when it rolls over the area of the MovieClip object.

  10. Next, you need to tell the circle instance to stop dragging when the mouse button releases. Underneath the last line of the code from Step 9, type the following code:

    circle.onRelease = circle.onReleaseOutside = function(){
      this.stopDrag();
      if ( eval(this._droptarget) == circleBig ) {
        statusMsg.gotoAndPlay ("correct");
      } else {
        this._x = 112;
        this._y = 316;
      }
    };

    This code uses the onRelease() method. The code for this method will be executed when the mouse button is released after a mouse click on the circle instance. The instance is told to stop dragging, and then ActionScript evaluates if the current instance (this) is dropped on top of circleBig. When the user drops any Movie Clip instance, the instance's _droptarget property is updated. The _droptarget property specifies the name of the Movie Clip instance upon which the dragged Movie Clip instance was last dropped. If no instance is underneath the dragged instance, _droptarget returns nothing (that is, an empty string). If the _droptarget is the large circle, then the dragged instance stays where it was dropped and the statusMsg instance plays its "Correct!" animation. Otherwise, the dragged instance (circle) returns to the X and Y coordinates of its starting point (112, 316).

    Note

    The eval() function is used to convert the slash syntax returned by _droptarget into a "real" object reference. On its own, _droptarget returns Flash Player 4-compatible syntax. In order to use it with current ActionScript routines, use the eval() function to return a proper object reference.

  11. Save your Flash document as movieclip_droptarget.fla, and test it (Ctrl+Enter or

    The statusClip symbol timeline with a Blur filter tween

You can continue this example with other shapes, using the same methodology. Create a separate onPress() and onRelease() method for each new drag interaction.

Note

For further study, we've included this basic drag-and-drop game as a sample document called movieclip_droptarget.fla in the ch25 folder of this book's CD-ROM. A more advanced example named movieclip_droptarget_adv.fla uses three different shapes, and assigns the handlers to each draggable clip with a for() loop and an array.

Making alpha, scale, and blur sliders

A compelling use of a draggable Movie Clip is a slider that can alter the properties of another object. By checking the position of a Movie Clip, you can use the position's X or Y coordinate value to alter the value of another Movie Clip. In this section, we show you how to create two sliders (one for alpha and another for scale) that will dynamically change the transparency and size of a Movie Clip instance on the Stage. Many thanks to Sandro Corsaro (http://sandrocorsaro.com) for supplying the artwork of our dog Stella and the park sign.

Note

You need to copy the slider_basic_starter.fla file from the ch25 folder of this book's CD-ROM. You'll use premade artwork to understand the functionality of startDrag, stopDrag, and duplicateMovieClip.

Assembling the parts

In this section, you set up the basic composition of the Stage, using elements from the slider_basic_starter.fla Library. You will add artwork of a dog and a park sign to the movie. The dog artwork will be duplicated using the duplicateMovieClip() method, and the duplicate instance will be manipulated by the sliders that you create in the next section. The park sign will be used to remove the duplicate instance using the _droptarget property and the removeMovieClip() method.

  1. Open your copy of the slider_basic_starter.fla. Resave this document as slider_basic_100.fla.

  2. Rename Layer 1 to dog_1.

  3. Access the document's Library by pressing Ctrl+L or

    Assembling the parts
  4. With the dogClip instance selected, open the Property inspector. In the <Instance Name> field, type dog_1, as shown in Figure 25.7.

    The dog_1 instance will be used as your reference MovieClip object. The scale and transparency of this dog instance will not be changed.

    Figure 25.7. The dog_1 instance will be used as your reference MovieClip object. The scale and transparency of this dog instance will not be changed.

  5. Using the Text tool, add the words Original Dog under the dog_1 instance. You don't need to make a new layer for this artwork.

  6. Create a new layer and name it sign. Move this layer below the dog_1 layer. Drag the parkSignClip symbol, located in the parkSignElements folder in the Library, to the lower-left corner of the Stage. In the Property inspector, assign the instance the name sign. In the Transform panel, reduce the size of the sign instance to 50%, as shown in Figure 25.8.

    The sign instance will be used to remove duplicates of the dog_1 Movie Clip instance.

    Figure 25.8. The sign instance will be used to remove duplicates of the dog_1 Movie Clip instance.

  7. Create a new layer called actions, and place it above all the other layers. Select the first keyframe of this layer. In the Actions panel, add the following actions:

    var dog_1:MovieClip;
       var dog_2:MovieClip = dog_1.duplicateMovieClip(
                                     "dog_2",
                                     1,
                                     {_x: 350,_y: 175 }
                                   );

    Tip

    You can insert line returns between arguments of a method, as demonstrated in this code sample. This practice makes the arguments easier to read on review.

    This line of code duplicates the instance dog_1, names the new instance dog_2, and places it on the first depth layer of the current timeline (_root). However, Flash Player 6 (or higher) ActionScript enables you to do a little more with the duplicateMovieClip() method. You can assign an initObject parameter that is passed to the duplicated instance. In this example, you create an object with _x and _y properties that are passed to the This argument positions the dog_2 instance at the X coordinate of 350 (350 pixels from the left corner of the Main Timeline Stage) and the Y coordinate of 175 (175 pixels down from the left corner).

  8. Save the Flash document, and test the movie (Ctrl+Enter or

    The sign instance will be used to remove duplicates of the dog_1 Movie Clip instance.
    The duplicateMovieClip() method creates a new instance of a MovieClip object. Unless you alter the new instance's X and Y positions, it will appear directly above the parent instance.

    Figure 25.9. The duplicateMovieClip() method creates a new instance of a MovieClip object. Unless you alter the new instance's X and Y positions, it will appear directly above the parent instance.

Now that you have some artwork on the Stage, you can manipulate the duplicated Movie Clip with a pair of dynamic sliders.

Building the sliders

In this section, you'll create two sliders: one for scale, and one for transparency. You'll need to make only one slider Movie Clip symbol and use a new instance for each slider. The basic "problems" of a dynamic slider are to (a) retrieve the position value of an object on the slider (you'll call this the slider bar), and (b) set the value of another object equal to (or some factor of) the position value of the slider bar. Finding the position of a slider bar is relatively straightforward. The difficulty lies in creating the value scale for the slider.

Because you have already determined the properties that will be altered (scale and transparency), you need to establish a range of values that each property can use. Luckily, both scale (as _xscale and _yscale in ActionScript) and transparency (as _alpha) use percentage units. However, scale can be any value that's greater than 0 percent and less than 3,200 percent. Alpha has a range of 0 to 100 percent. If you want to use the same parent slider for each property slider, you need to manipulate the position values of the slider bar differently for each property. Let's start with building the basic slider.

Note

Resume using the same file you finished in the previous section. Otherwise, you can open a copy of slider_basic_100.fla, located in the ch25 folder of this book's CD-ROM.

  1. Resave the slider_basic_100.fla file as slider_basic_101.fla.

  2. Create a new Movie Clip symbol (Ctrl+F8 or

    Building the sliders
  3. With the sliderRule graphic selected, open the Info panel. On the right side of the Info panel (on the diagram of the square bounding box), make sure that the registration point is set to the top-left corner of the selection's bounding box. Then enter the values −28 for the X coordinate and −12 for the Y coordinate, as shown in Figure 25.10.

    The sliderRule's starting point (just to the right of the first left-hand circle) needs to be at the slider Movie Clip's zero X coordinate.

    Figure 25.10. The sliderRule's starting point (just to the right of the first left-hand circle) needs to be at the slider Movie Clip's zero X coordinate.

  4. Create another layer for the sliderClip symbol and name it pos. Drag an instance of the sliderBar Movie Clip (located in the sliderBarElements folder of the Library) to the sliderClip Movie Clip Stage.

  5. With the sliderBar instance selected, open the Transform panel. Type 90 in the Rotate field, and press Enter. In the Info panel, enter 100 for the X coordinate and 0 for the Y coordinate.

  6. To control the position of the sliderBar instance with ActionScript, you need to assign a unique instance name. Select the sliderBar instance and type pos in the <Instance Name> field of the Property inspector, as shown in Figure 25.11.

    The starting X coordinate for the pos Movie Clip instance is set to 100. When the Flash movie starts, this value will be applied to the scale and alpha properties of the dog_2 instance on the Main Timeline.

    Figure 25.11. The starting X coordinate for the pos Movie Clip instance is set to 100. When the Flash movie starts, this value will be applied to the scale and alpha properties of the dog_2 instance on the Main Timeline.

  7. Now you need to make the pos Movie Clip instance draggable. In this example, you're going to make a button-free draggable Movie Clip instance, using the newer onPress() and onRelease() methods for MovieClip objects—just as you did in the earlier exercise. Create a new layer in the sliderClip symbol, name it actions, and move it above the pos layer. Open the Actions panel (F9). Type the following code in the Script pane:

    var pos:MovieClip;
    pos.onPress = function():Void{
      this.startDrag(true, 0, 0, 200, 0);
    };

    To make the position instance draggable, you need to detect a mouse press event on the pos instance. When a mouse click occurs on the instance, the actions nested within the onPress() function are executed.

    The second line of code enables the dragging behavior of the pos instance by using the startDrag() method on this. Because it's used as a method and not as an action, you don't need to specify a target instance in the arguments. The arguments prescribed here lock the mouse to the center of the object and constrain the draggable region to a bounding box defined by 0, 0 and 200, 0. This effectively keeps the pos instance confined to the line of the sliderRule graphic.

  8. Next, you need to be able to stop dragging the pos object when the mouse button is released. You'll use the onRelease() handler to define your actions. Open the Actions panel for frame 1 of the actions layer. Type the following code after the last curly brace of the onPress() function:

    pos.onRelease = pos.onReleaseOutside = function():Void {
      this.stopDrag();
    };

    This block of code performs in the same manner that your code in Step 7 did. Once a mouse release event (the act of releasing the left mouse button) is detected (line 1), you stop the dragging of the pos instance initiated in Step 7 (line 3).

    In the following step, you'll create two instances of the sliderClip symbol on the Main Timeline Stage: one for scale, and one for alpha.

  9. Exit Edit mode, and return to the Scene 1 Timeline (the Main Timeline). Create a new layer called scaleSlider. Open the Library and drag an instance of the sliderClip to the Stage. Name this instance scaleSlider in the Property inspector.

  10. Move the scaleSlider instance to the lower right of the Stage.

  11. Create another layer called alphaSlider. Drag another instance of the sliderClip symbol onto the Stage, and name the instance alphaSlider. Rotate this instance −90 degrees. Place the instance just left of center of the Stage, as shown in Figure 25.12.

    At this point, your Flash document's Stage should contain the dogClip and parkSignClip artwork, as well as two instances of the sliderClip symbol.

    Figure 25.12. At this point, your Flash document's Stage should contain the dogClip and parkSignClip artwork, as well as two instances of the sliderClip symbol.

  12. Save your Flash document, and test it. You should be able to drag the position bars on both sliders.

Checking the positions of the sliders

Once you have a slider bar that is draggable, you need to access the new values of the pos instance and apply the values to the properties of the To do this, you need to have an event handler whose sole job is to check the X coordinate of the pos instance. In this section, you'll learn how to make an onEnterFrame() handler on the Main Timeline.

Note

Resume using the Flash document that you created in the last section. If you didn't complete that section, make a copy of the slider_basic_101.fla file located in the ch25 folder of this book's CD-ROM.

  1. Save the slider_basic_101.fla file as slider_basic_102.fla.

  2. Select frame 1 of the actions layer in the Main Timeline (that is, Scene 1). Open the Actions panel. In the Script pane, after the duplicateMovieClip() action, type the following code:

    var scaleSlider:MovieClip;
    var alphaSlider:MovieClip;
    
       this.onEnterFrame = function():Void {
       var scaleVal:Number = scaleSlider.pos._x;
       var alphaVal:Number = alphaSlider.pos._x;
       with (dog_2) {
          _xscale = scaleVal;
          _yscale = scaleVal;
          _alpha = alphaVal;
       }
    };

    Because the event method onEnterFrame() is specified for the Main Timeline (this), this block of code will execute continuously in your Flash movie. Why? Any timeline will continuously enter a frame for playback, even if a stop() action is applied to all timelines. The speed at which the enterFrame event occurs is determined by the frame rate of the Flash movie (as defined by the Modify

    Checking the positions of the sliders

    What happens on each execution of the onEnterFrame() handler? The second and third lines of code create variables that reference the X positions of the pos instances with your two sliders. The fourth line of code uses the with() action to target the dog_2 object with the remaining nested actions. The fifth and sixth lines of code set the X and Y scale properties of the dog_2 instance to the value returned by the current X coordinate of the pos instance (relative to the coordinates within the sliderClip symbol) nested within the scaleSlider instance. The seventh line sets the _alpha property of the dog_2 instance equal to the X coordinate of the pos instance within the alphaSlider instance.

  3. Save your Flash document, and test it. When you drag the bar on the bottom scale slider, notice how the size of the dog_2 instance increases as you drag it to the right. When you drag the bar down on the left alpha slider, you'll see that the opacity of the dog_2 instance decreases.

    Note

    You may be wondering why the X coordinate of the pos instance is used for the alphaSlider instance, instead of the Y coordinate. Indeed, you do drag the bar on a vertical axis instead of a horizontal one. However, the pos instance exists within the space of the sliderClip symbol, which has a horizontal orientation in the Edit mode. The X coordinate is derived from the Stage of the Edit mode, regardless of the instance's orientation.

    Okay, you have the sliders changing the size and opacity of the However, nothing happens as you drag the bar on the alphaSlider instance toward its upper limit. Because the X coordinate of the pos instance starts at 100, you won't see any visual effect to the _alpha property as it increases beyond 100 percent. Therefore, it would be better to have the alphaSlider slider convert the X coordinate of the pos instance to a true 0 to 100 range of values.

    To do this, you need to develop an equation that will do the work of automatically remapping values to a 0–100 scale. We know that the lowest X coordinate of the pos instance is 10, and that the highest X coordinate is 200. If you want the highest position of the bar to provide 100 percent opacity, then you need to divide 200 by a number that will give you 100. Dividing 200 by 2 returns 100. How does that work for the low end? If the X coordinate returns the lowest value of 10, then your lowest opacity value will be 5.

  4. With frame 1 of the actions layer of the Main Timeline selected, open the Actions panel (F9, or Option+F9 on Mac), and modify the seventh line of the onEnterFrame() handler function to read:

    _alpha = alphaVal/2;
  5. Save your Flash document and test it. Now, as you drag up with the bar for the alphaSlider instance, the opacity increases. As you drag down, it decreases.

    So far, so good. However, it would be useful if the alphaSlider's pos instance started with an X coordinate of 200. This would initialize the dog_2 instance with an opacity of 100 percent. You could physically move the pos instance within the sliderClip symbol to an X coordinate of 200, but that would increase the scale of the dog_2 instance to 200 percent at the start. To change only the pos instance of alphaSlider at the start of the movie, you'll add another line of code to frame 1 of the actions layer on the Main Timeline.

  6. Select frame 1 of the actions layer, and open the Actions panel. Add the following code to the Script pane, after all of the existing code:

    alphaSlider.pos._x = 200;

    This block of code will execute once, when the pos instance (a Movie Clip object) first appears (or loads) on the Stage.

  7. Save the Flash document and test it. This time, the alphaSlider's bar (its pos instance) will immediately start at the upper limit.

  8. Now, let's take advantage of the new filter effects available in Flash Player 8. Create a new layer on your Main Timeline (that is, Scene 1), and name it blurSlider. Make a copy of the scaleSlider instance and paste it on frame 1 of the blurSlider layer.

  9. Name the new copied instance blurSlider in the Property inspector, and position the instance near the top of the alphaSlider instance, parallel to the scaleSlider instance.

  10. To enable a blur effect with this slider, you need to modify the code in the onEnterFrame() handler on frame 1 of the actions layer. Select this frame, and open the Actions panel. Modify the onEnterFrame() handler with the bold code shown below. Do not type the

    Checking the positions of the sliders
    var blurSlider:MovieClip;
    
    this.onEnterFrame = function():Void {
       var scaleVal:Number = scaleSlider.pos._x;
       var alphaVal:Number = alphaSlider.pos._x;
    var blurVal:Number = blurSlider.pos._x;
       var bf:flash.filters.BlurFilter = new 
    Checking the positions of the sliders
    flash.filters.BlurFilter(); bf.blurX = blurVal/2; bf.blurY = blurVal/2; bf.quality = 3; with (dog_2) { _xscale = scaleVal; _yscale = scaleVal; _alpha = alphaVal/2; filters = [bf]; } };

    This code creates a new BlurFilter instance named bf. The same calculation used for the alpha value is used for the blur quantities, blurX and blurY. The bf filter is applied to the dog_2 instance's filter property at the end of the with() statement.

  11. Save the Flash document, and test the movie. The dog_2 instance should now initialize with a blurred look, as shown in Figure 25.13.

    The new BlurFilter effect applied to the dog_2 instance.

    Figure 25.13. The new BlurFilter effect applied to the dog_2 instance.

  12. In order to keep a clear visual of the dog_2 instance when the movie first loads, add this line of code to the end of the script on frame 1 of the actions layer:

    blurSlider.pos._x = 0;
  13. Save the Flash document, and test it. Now, the blurSlider instance initializes a blurX and blurY value of 0.

Removing Movie Clips

At this point in the chapter, you have three sliders that dynamically control the scale and alpha of the dog_2 Movie Clip instance on the Stage. What if you wanted to get rid of the dog_2 instance? How would you delete it? The only way to remove a duplicated Movie Clip instance is to use the removeMovieClip() method or action. In this section, we show you how to use the _droptarget property and the removeMovieClip() method of the MovieClip object.

Note

Resume using the same document, slider_basic_102.fla, that you created in the last section. Alternatively, you can open the slider_basic_102.fla file located in the ch25 folder of this book's CD-ROM.

  1. Select frame 1 of the actions layer on the Main Timeline, and open the Actions panel. Type the following code after the last line of ActionScript currently in the Script pane:

    dog_2.onPress = function():Void{
      this.startDrag (true, 0, 0, 550, 400);
    };
    dog_2.onRelease = dog_2.onReleaseOutside = function():Void{
      this.stopDrag ();
      if(eval(this._droptarget) == sign){
        this._parent.onEnterFrame = null;
        this.removeMovieClip();
      }
    };

    Most of this code is already familiar to you. Here you want to make only your duplicate dog instance (dog_2) draggable.

    When a mouse press event is detected on the dog_2 instance, the function declared within the onPress() method for dog_2 will execute. The startDrag() method of the current dog instance (this) will be enabled and constrained to the dimensions of the Flash movie Stage.

    When a mouse release event is detected over the dog_2 instance, then the stopDrag() method will be executed. The last if statement checks whether the _droptarget property of the current dog instance is equal to the target path of the sign instance. If the dog_2 instance is over the sign instance on the Stage when the dragging stops, then the current dog instance is removed.

    Finally, if the dog_2 instance is removed, you must reset the onEnterFrame() method assigned to the Main Timeline, the parent of the dog_2 instance—otherwise, the onEnterFrame() method will generate errors in the Output window. By assigning a value of null to the Main Timeline's onEnterFrame() handler, the function established earlier will be deleted.

    Note

    We use the eval() action on the _droptarget property because _droptarget returns the path of the target in Slash notation (for Flash Player 4 compatibility). If we use eval() on the _droptarget property, Flash returns the target path in dot syntax, as a true object reference.

  2. Save your Flash document as slider_basic_103.fla, and test it. When you drag the dog_2 instance over the sign instance, the dog_2 instance disappears.

Note

You can find a completed version of slider_basic_103.fla in the ch25 folder of this book's CD-ROM. Another version, slider_basic_104.fla, has a button handler to re-duplicate the dog_2 instance and re-organize the actions within a function.

In the next chapter, you expand your knowledge of ActionScript code by using functions and arrays. These code devices enable you to organize code and data much more efficiently with ActionScript.

Note

We'd like to know what you think about this chapter. Visit www.flashsupport.com/feedback to send us your comments.

Summary

  • The MovieClip class has unique properties, methods, and handlers. Using dot syntax, you can access these characteristics of a MovieClip object.

  • You can change a MovieClip instance's position, scale, and rotation using ActionScript. Most physical attributes are accessed by specifying the Movie Clip's path followed by the property name, as in instance._rotation.

  • You can create draggable Movie Clips in ActionScript without using any Button instances, by using the onPress() and onRelease() methods of the MovieClip object.

  • The _droptarget property of Movie Clip instance (instance A) indicates the path of the Movie Clip instance (instance B) upon which a Movie Clip instance (instance A) is dropped.

  • As the sliders example demonstrated, you can use the values of one MovieClip instance's properties to change the property values of another MovieClip instance.

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

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