Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

7

Controlling Movie Clips

Macromedia Flash gives you an incredible number of creative opportunities, and the movie clip is the digital canvas for your ideas. Regardless of whether you are interested in creating animations that treat the senses, games that entertain, or applications that help with productivity, mastering the movie clip is the key to exercising your creativity.

With Macromedia Flash, you can create your projects by manually piecing them together in the timeline, by creating a project entirely from script, or through a mixture of code and manual assembly on the timeline. There is no one right way to do it, just the way that best fits your needs.

This chapter teaches you a number of techniques to get you well on your way to mastering movie clips. You learn how to create movie clips on-the-fly, how to load external content, how to pull content to the stage from different sources, and how to manipulate content once it is there. You also take a look at how to use movie clips as masks, and learn about some performance issues surrounding movie clips.

The Movie Clip Revealed

You have already learned the three types of symbols that you can work with: graphic, button, and movie clip. The graphic symbol is used for holding media that does not require its own timeline. It cannot be controlled with ActionScript, so its usefulness for coding is very limited. The button clip can be controlled with script, but it is primarily just a source for events, and can be controlled only in limited ways. The movie clip can be completely controlled with ActionScript, and has many methods available to use. These methods are introduced shortly.

You have also already learned that Macromedia Flash works on the principle of a timeline. Each movie clip has its own timeline, so each movie clip can independently position, size, and otherwise control all of its own content. The timeline is split up into frames. If the frame rate for the project is set to 15 frames per second, then every 1/15th of a second each movie clip has an opportunity to make a change to any of its content, either through tweens or through script.

Many methods, properties, and events are available for you to use in controlling a movie clip through script. Some of these are defined in the following sections.

Chapter 7

MovieClip Class Methods

The movie clip comes with its own set of tools in the form of methods. Methods such as attachMovie(), createEmptyMovieClip(), and duplicateMovieClip() enable you to create movie clip containers, either empty or already populated with content. Drawing methods such as moveTo(), lineTo(), curveTo(), beginFill(), and endFill() enable you to create script-generated shapes within a movie clip. The following table describes many of the methods that the movie clip makes available to you:

Method

Returns

Description

 

 

 

attachBitmap

Nothing

Attaches a bitmap object to an empty movie clip. (Flash

 

 

Player 8 only)

attachMovie

Movie clip

Makes a copy of a movie clip from the library and places

 

 

the copy inside the specified movie clip on the stage.

beginFill

Nothing

Indicates that the shape to be drawn using the movie clip

 

 

drawing methods should be filled in.

clear

Void

Clears a movie clip of all shapes drawn inside using the

 

 

movie clip drawing methods.

createEmpty

Movie clip

Creates a new empty movie clip inside another

MovieClip

 

movie clip.

createTextField

Text field

Creates a new text field inside a movie clip.

duplicate

Movie clip

Makes a copy of an existing movie clip.

MovieClip

 

 

endFill

Nothing

Indicates that subsequent lines drawn using the movie clip

 

 

drawing methods should not add to the filled-in shape.

getBytesLoaded

Number

Gets the number of bytes loaded of an externally loaded

 

 

movie clip.

getBytesTotal

Number

Gets the total number of bytes of an externally loaded

 

 

movie clip.

getURL

Nothing

Calls a browser window to load content from the

 

 

specified URL.

gotoAndPlay

Nothing

Moves the playhead for the specified movie clip to a

 

 

specific frame and then continues playing.

hitTest

Boolean

Determines whether two movie clips overlap each other.

lineStyle

Nothing

Sets visual characteristics of subsequent lines drawn

 

 

using the movie clip drawing methods.

lineTo

Nothing

Draws a line from the current position to the specified x

 

 

and y coordinates.

 

 

 

160

 

 

 

Controlling Movie Clips

 

 

 

 

 

 

 

 

 

Method

Returns

Description

 

 

 

 

 

loadMovie

Nothing

Loads external content into the designated movie clip.

 

moveTo

Nothing

Moves the drawing marker to the specified x and y coor-

 

 

 

dinates without drawing a line.

 

play

Nothing

Starts playback of the specified movie clip from where

 

 

 

the playhead last stopped.

 

removeMovieClip

Nothing

Removes a movie clip that has been added to the stage

 

 

 

using attachMovie(), createEmptyMovieClip(), or

 

 

 

duplicateMovieClip().

 

setMask

Nothing

Uses a second movie clip to designate which parts of the

 

 

 

specified movie clip are visible.

 

startDrag

Nothing

Enables the user to drag a movie clip around the screen.

 

stop

Nothing

Stops playback for the specified movie clip.

 

stopDrag

Nothing

Stops a draggable movie clip from being dragged.

 

swapDepths

Nothing

Swaps the stacking order of two movie clips, or moves a

 

 

 

movie clip to a specific depth.

 

unloadMovie

Nothing

Unloads the contents of a movie clip that has been popu-

 

 

 

lated through loadMovie().

The following sections illustrate how to use the methods and provide each method’s prototype. A prototype is an example of a method that shows all the possible input values along with their data types, as well as the data type of any return value. Any parameters that are in square brackets are optional and can be omitted from the method call, if desired.

attachBitmap()

The Bitmap object, which is new to Flash Player version 8, allows pixels to be individually manipulated. It gives great power for controlling animation, but requires more code to do it. A Bitmap object is not visible until it is linked up to a movie clip. The attachBitmap() method performs this linkage, making the bitmap visible within the designated movie clip.

The attachBitmap()method takes between two and four parameters. The first is a handle to a Bitmap instance. The second is a movie clip depth to use for the bitmap. The third, which is optional, sets whether the pixels in the bitmap object automatically snap to the nearest screen pixel location. Possible values are auto (the default), always, and never. The final parameter, also optional, sets whether the bitmap should be smoothed when scaled. The default value is true. The following prototype shows the basic form of the attachBitmap() method:

baseMovie.attachBitmap(bmpData:BitmapData, depth:Number, [pixelSnapping:String],;

[smoothing:Boolean]) : Void

161

Chapter 7

Here’s an example of using attachBitmap():

import flash.display.*;

this.createEmptyMovieClip(“bitmapHolder”, this.getNextHighestDepth()); var bmpData:BitmapData = new BitmapData(100, 100, false, 0x000066); bitmapHolder.attachBitmap(bmpData, bitmapHolder.getNextHighestDepth());

Updates to bitmaps take effect immediately. The player does not wait for the next frame to be processed before updating the display.

attachMovie()

The attachMovie()method is used for making copies of library symbols and placing them onstage. It takes either three or four parameters. The first is the linkage ID for the library symbol to be attached. The linkage ID for a symbol is set in the symbol’s library properties. The second parameter is an instance name to give the new movie clip instance. The third is a movie clip depth to use for the new instance. The fourth parameter, which is optional, allows initialization properties to be passed to the new instance. The following prototype shows the basic form of the attachMovie() method:

baseMovie.attachMovie(id:String, name:String, depth:Number, ;

[initObject:Object]) : MovieClip

Here’s an example of using attachMovie() to create a copy of the movie clip with linkage ID “templateClip”. It gives the new copy the name “newClip”, sets the depth to be the next highest one available in the current timeline, and sets the _x and _y properties to 20:

this.attachMovie(“templateClip”, “newClip”, this.getNextHighestDepth(), ;

{_x:20, _y:20});

beginFill()

beginFill() works in combination with moveTo(), lineTo(), and endFill() and defines an area in which to draw a solid shape. It takes two parameters: the first is the fill color to use, and the second is the transparency of the fill, with 100 being fully opaque. The following prototype shows the basic form of the beginFill() method:

baseMovie.beginFill(color:Number, alpha:Number) : Void

Here’s an example of using beginFill(), showing the creation a blue triangle:

this.createEmptyMovieClip(“triangleClip”, this.getNextHighestDepth()); triangleClip.moveTo(50, 0);

triangleClip.beginFill(0x000066, 100); triangleClip.lineTo(0, 100); triangleClip.lineTo(100, 100); triangleClip.lineTo(50, 0); triangleClip.endFill();

If the starting and ending points are not the same, a line automatically connects them and the resulting shape is filled.

162

Controlling Movie Clips

clear()

Over time, repeated use of the drawing methods to draw inside a movie clip that stays on the stage all the time induces additional processor and memory overhead. Even if drawing one shape completely obscures another shape, the original shape still takes up memory and is part of the drawing routine. The clear() method removes all shapes from the drawing cycle and should be used periodically for heavy drawing routines to keep the movie running quickly.

This method takes no parameters. Here’s its prototype:

myMovieClip.clear() : Void

This method does not touch shapes manually created in the movie clip from the development environment’s drawing tools, nor does it remove nested movie clips.

createEmptyMovieClip()

The createEmptyMovieClip()method is very important to drawing out screen content with ActionScript. It is used for creating containers for other content, such as drawn-out shapes, loaded content, and components.

It takes two parameters. The first is a string representing the instance name of the new movie clip, and the second is a depth to place the new clip. This is one of the core methods used to build content at runtime. Here is its prototype:

baseMovie.createEmptyMovieClip(name:String, depth:Number) : MovieClip

createTextField()

The createTextField() method is the equivalent of creating a dynamic text field on the stage with the text tool, and is one of the core methods for building content at runtime.

This method takes six parameters. The first is a string representing the instance name of the new movie clip, and the second is a depth to place the new text field. The next two are x and y coordinates for placing the text field, and the last two set the width and the height. The following method prototype shows the basic form of createTextField():

baseMovie.createTextField(name:String, depth:Number, x:Number, y:Number, ;

width:Number, height:Number) : TextField

duplicateMovieClip()

The duplicateMovieClip() method is used for duplicating existing content on the stage. Its use has diminished since the addition of the attachMovie() method.

Two forms of duplicateMovieClip() exist. The first takes either two or three parameters: a string representing the instance name of the new movie clip, a depth to place the new movie clip, and, optionally, an Object instance containing properties to pass to the new movie clip. Here’s the method prototype for duplicateMovieClip():

baseMovie.duplicateMovieClip(name:String, depth:Number, ;

[initObject:Object]) : MovieClip

163

Chapter 7

The following example creates an empty movie clip, draws a triangle in that clip, duplicates the movie clip, and moves the new clip to a different location on the screen. This results in two triangles being shown on the screen:

this.createEmptyMovieClip(“triangleClip”, this.getNextHighestDepth()); triangleClip.moveTo(50, 0);

triangleClip.beginFill(0x000066, 100); triangleClip.lineTo(0, 100); triangleClip.lineTo(100, 100); triangleClip.lineTo(50, 0); triangleClip.endFill();

triangleClip.duplicateMovieClip(“newClip”, this.getNextHighestDepth(), ; {_x:50, _y:50});

The second form of this method is actually a global function, not a movie clip method. The following prototype shows the basic form of the duplicateMovieClip() global function:

duplicateMovieClip(target:MovieClip, name:String, depth:Number) : Void

This function was commonly used in version 4 of the Flash plug-in; before the attachMovie() method was introduced, it was the only way to duplicate movie clips programmatically. In general, it’s better either to use attachMovie() to create new movie clip instances from the library, or to use the first form of duplicateMovieClip().

endFill()

endFill() works in combination with the beginFill(), moveTo(), and lineTo() methods and defines an area in which to draw a solid shape. This method takes no arguments. The following prototype shows the basic form of endFill():

baseClip.endFill() : Void

Here’s an example that draws a blue triangle on the screen:

this.createEmptyMovieClip(“triangleClip”, this.getNextHighestDepth()); triangleClip.moveTo(50, 0);

triangleClip.beginFill(0x000066, 100); triangleClip.lineTo(0, 100); triangleClip.lineTo(100, 100); triangleClip.lineTo(50, 0); triangleClip.endFill();

As a matter of interest, this method does not perform any fill operation. The fill is actually drawn in every time the lineTo() method is called. The endFill() method tells future lineTo() calls not continue to add to the filled-in shape.

getBytesLoaded()

The getBytesLoaded() method is used in conjunction with getBytesTotal() for movie clip preloader code. A repeated call to check the bytes loaded is made, and when the bytes loaded and the total bytes are the same, the loaded movie can be played. This method takes no arguments. Here’s the prototype of its basic form:

164

Controlling Movie Clips

baseClip.getBytesLoaded() : Number

The following example shows getBytesLoaded() used as part of a pre-loader:

var intervalId:Number;

this.createEmptyMovieClip(“loadedMovie”, this.getNextHighestDepth()); this.createTextField(“percentLoadedField”, this.getNextHighestDepth(), 10, 10, ;

100, 20);

function checkLoadProgress()

{

if (loadedMovie.getBytesTotal() > 0)

{

loadedMovie.stop();

percentLoadedField.text = String(Math.ceil(loadedMovie.getBytesLoaded() ;

/ loadedMovie.getBytesTotal() * 100)) + “%”;

if (loadedMovie.getBytesTotal() - loadedMovie.getBytesLoaded() == 0)

{

clearInterval(intervalId);

loadedMovie.play();

}

}

}

loadedMovie.loadMovie(“http://www.nathanderksen.com/book/sampleAnimation.swf”); intervalId = setInterval(checkLoadProgress, 100);

Chapter 8 covers this topic in greater detail.

There is a brief period of time at the beginning of the load process where getting a percentage loaded value by dividing the results of the getBytesLoaded() call by the results of getBytesTotal()returns an undefined number. During this time, subtracting getBytesLoaded() from getBytesTotal()returns 0 in the same way that it does when the movie has loaded completely. Check that getBytesTotal() returns a non-zero value before using both of these methods to calculate progress.

getBytesTotal()

getBytesTotal() is used in conjunction with the getBytesLoaded() method for movie clip preloader code. It returns zero bytes until it can find out the size of the file to download. This method takes no arguments. The following prototype shows its basic form:

baseClip.getBytesTotal() : Number

A sample implementation of this method used as part of a pre-loader might look like this:

var intervalId:Number;

this.createEmptyMovieClip(“loadedMovie”, this.getNextHighestDepth()); this.createTextField(“percentLoadedField”, this.getNextHighestDepth(), 10, 10, ;

100, 20);

function checkLoadProgress()

{

165

Chapter 7

if (loadedMovie.getBytesTotal() > 0)

{

loadedMovie.stop();

percentLoadedField.text = String(Math.ceil(loadedMovie.getBytesLoaded() ; / loadedMovie.getBytesTotal() * 100)) + “%”;

if (loadedMovie.getBytesTotal() - loadedMovie.getBytesLoaded() == 0)

{

clearInterval(intervalId);

loadedMovie.play();

}

}

}

loadedMovie.loadMovie(“http://www.nathanderksen.com/book/sampleAnimation.swf”); intervalId = setInterval(checkLoadProgress, 100);

Chapter 8 covers this topic in greater detail.

getURL()

The getURL() method is used to replace the Web page containing the Flash movie with a new page, to open a Web page in another window, or to communicate with the browser using JavaScript.

Both movie clip method and global function versions of this call exist. The movie clip method takes between one and three parameters. The first parameter is a URL for a resource to load in the browser window containing the Macromedia Flash movie. The optional second parameter is a string designating the name of a different target browser window. The optional third parameter sets a method for submitting variables to a target server-side script, with possible values being GET or POST. The following prototype shows getURL()’s basic form:

baseClip.getURL(url:String, [windowName:String], [method:String]) : Void

Here’s an example implementation:

myMC.getURL(“http://www.apple.com/”, “_blank”); // Load Web page into a new window myMC.getURL(“newPage.html”); // Load Web page into the current window getURL(“javascript:alert(‘The quick brown fox’);”); // Call a JavaScript function

Both versions of getURL() can be used to call any URL that could potentially be typed in the browser address bar, not just web pages.

The global function version of this method takes between one and three parameters. The first is a URL for a resource to load in the browser window containing the Macromedia Flash movie. The optional second parameter is a string designating the name of a different target browser window.

The optional third parameter is a string holding name/value pairs to send to the server in the form of &var1=value1&var2=value2. Here’s the prototype of the basic getURL() global function:

getURL(url:String, windowName:String, [variables:String]) : Void

The LoadVars and the XML classes are preferred ways to send data to a server.

166

Controlling Movie Clips

The global function version of getURL() is preferred over the method version. The method version does not actually depend on the movie clip it is called from unless it is being used to send variables to the server.

gotoAndPlay()

gotoAndPlay() has both movie clip method and global function versions. The movie clip method takes one parameter, which is either the number of or a string label for the label of the frame from which to start playing. This method controls the playhead within the specified movie clip. Here’s its prototype:

baseClip.gotoAndPlay(frame:Object) : Void

Following are examples of a call made with each parameter:

myMC.gotoAndPlay(20);

myMC.gotoAndPlay(“photographyScreen”);

Using frame labels rather than frame numbers is preferred, but frame labels can be applied only in the Flash development environment and can’t be set at runtime.

The global function version of gotoAndPlay() takes two parameters. The first, the name of a scene to target, is optional. The second parameter is either the number or string label of the frame from which to start playing. This function controls the playhead on the base timeline. Here’s the prototype of its basic form:

gotoAndPlay(frame:Object) : Void

It is highly recommended that you avoid using scenes, especially for ActionScript programming. They result in more complicated code, and numerous issues are associated with accessing scenes with ActionScript.

hitTest()

The hitTest() method is used to detect whether two movie clips are overlapping each other. It can be used for collision detection in games, but it is limited in that it uses a rectangle around both movie clips to test for overlapping. If the contents of the movie clips are not rectangular, the method may return true even if the contents of the two clips are not actually visibly overlapping.

hitTest() takes a single parameter, which is a handle to the movie clip to compare with. The following prototype shows the method’s basic form:

baseClip.hitTest(targetMovie:MovieClip) : Boolean

The following example shows the method in use. Two movie clips containing triangles are created, and the first one is made draggable. When it is dragged over the second triangle and the mouse is released, a trace statement indicates that the movie clips overlap:

this.createEmptyMovieClip(“triangle1Clip”, this.getNextHighestDepth()); triangle1Clip.moveTo(50, 0);

triangle1Clip.beginFill(0x000066, 100); triangle1Clip.lineTo(0, 100);

167