What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Work with MovieClips in Flash

About controlling movie clips with ActionScript

Calling multiple methods on a single movie clip

Loading and unloading SWF files

Specifying a root timeline for loaded SWF files

Loading image files into movie clips

Changing movie clip position and appearance

Dragging movie clips

Creating an empty movie clip

Duplicating or removing a movie clip

Attaching a movie clip symbol to the Stage

Adding parameters to dynamically created movie clips

Determining the next highest available depth

Determining the instance at a particular depth

Determining the depth of an instance

Swapping movie clip depths

When to enable caching

Caching a movie clip

Setting the background of a movie clip

Using movie clips as masks

About masking device fonts

About alpha channel masking

Assigning a class to a movie clip symbol

Controlling member access in your classes

 

About controlling movie clips with ActionScript

TOP

You can use global ActionScript functions or the methods of the MovieClip class to perform tasks on movie clips. Some methods of the MovieClip class perform the same tasks as functions of the same name; other MovieClip methods, such as hitTest() and swapDepths(), don't have corresponding function names.

The following example shows the difference between using a method and using a function. Each statement duplicates the instance my_mc, names the new clip new_mc, and places it at a depth of 5.

my_mc.duplicateMovieClip("new_mc", 5);

duplicateMovieClip(my_mc, "new_mc", 5);

When a function and a method offer similar behaviors, you can select to control movie clips by using either one. The choice depends on your preference and your familiarity with writing scripts in ActionScript. Whether you use a function or a method, the target timeline must be loaded in Flash Player when the function or method is called.

To use a method, activate it by using the target path of the instance name, a dot (.), and then the method name and parameters, as shown in the following statements:

myMovieClip.play();

parentClip.childClip.gotoAndPlay(3);

In the first statement, play() moves the playhead in the myMovieClip instance. In the second statement, gotoAndPlay() sends the playhead in childClip (which is a child of the instance parentClip) to Frame 3 and continues to move the playhead.

Global functions that control a timeline have a target parameter that let you specify the target path to the instance that you want to control. For example, in the following script startDrag() targets the instance the code is placed on and makes it draggable:

my_mc.onPress = function() {

startDrag(this);

};

my_mc.onRelease = function() {

stopDrag();

};

The following functions target movie clips: loadMovie(), unloadMovie(), loadVariables(), setProperty(), startDrag(), duplicateMovieClip(), and removeMovieClip(). To use these functions, you must enter a target path for the function's target parameter to indicate the target of the function.

The following MovieClip methods can control movie clips or loaded levels and do not have equivalent functions: MovieClip.attachMovie(), MovieClip.createEmptyMovieClip(),

MovieClip.createTextField(), MovieClip.getBounds(), MovieClip.getBytesLoaded(), MovieClip.getBytesTotal(), MovieClip.getDepth(), MovieClip.getInstanceAtDepth(),

MovieClip.getNextHighestDepth(), MovieClip.globalToLocal(), MovieClip.localToGlobal(), MovieClip.hitTest(), MovieClip.setMask(), MovieClip.swapDepths().

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation.

You can find samples of photo gallery applications on your hard disk.These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file, which includes scripted animation. You can find the sample source files, gallery_tree.fla and gallery_tween.fla, in the Samples folder on your hard disk.

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.

 

Calling multiple methods on a single movie clip

TOP

You can use the with statement to address a movie clip once and then execute a series of methods on that clip. The with statement works on all ActionScript objects (for example, Array, Color, and Sound)--not only movie clips.

The with statement takes a movie clip as a parameter. The object you specify is added to the end of the current target path. All actions nested inside a with statement are carried out inside the new target path, or scope. For example, in the following script, the donut.hole object passes to the with statement to change the properties of hole:

with (donut.hole) {

_alpha = 20;

_xscale = 150;

_yscale = 150;

}

The script behaves as if the statements inside the with statement were called from the timeline of the hole instance. The preceding code is equivalent to the following example:

donut.hole._alpha = 20;

donut.hole._xscale = 150;

donut.hole._yscale = 150;

The preceding code is also equivalent to the following example:

with (donut) {

hole._alpha = 20;

hole._xscale = 150;

hole._yscale = 150;

}

 

Loading and unloading SWF files

TOP

To play additional SWF files without closing Flash Player, or to switch SWF files without loading another HTML page, you can use one of the following options:

  • The global loadMovie() function or loadMovie() method of the MovieClip class.

  • The loadClip() method of the MovieClipLoader class.

You can also use the loadMovie() method to send variables to a CGI script, which generates a SWF file as its CGI output. For example, you might use this procedure to load dynamic SWF or image files based on specified variables within a movie clip. When you load a SWF file, you can specify a level or movie clip target into which the SWF file loads. If you load a SWF file into a target, the loaded SWF file inherits the properties of the targeted movie clip. After the Flash movie is loaded, you can change those properties.

The unloadMovie() method removes a SWF file previously loaded by the loadMovie() method. Explicitly unloading SWF files with unloadMovie() ensures a smooth transition between SWF files and can decrease the memory that Flash Player requires. It can be more efficient in some situations to set the movie clip's _visible property to false instead of unloading the clip. If you might reuse the clip at a later time, set the _visible property to false and then set to true when necessary.

Use loadMovie() to do any of the following:

  • Play a sequence of banner ads that are SWF files by placing a loadMovie() function in a container SWF file that sequentially loads and unloads SWF banner files.

  • Develop a branching interface with links that lets the user select among several SWF files that are used to display a site's content.

  • Build a navigation interface with navigation controls in level 0 that loads content into other levels. Loading content into levels helps produce smoother transitions between pages of content than loading new HTML pages in a browser.

 

Specifying a root timeline for loaded SWF files

TOP

The _root ActionScript property specifies or contains a reference to the root timeline of a SWF file. If a SWF file has multiple levels, the root timeline is on the level that contains the currently executing script. For example, if a script in level 1 evaluates _root, _level1 is returned. However, the timeline that _root specifies can change, depending on whether a SWF file is running independently (in its own level) or was loaded into a movie clip instance by a loadMovie() call.

In the following example, consider a file named container.swf that has a movie clip instance named target_mc on its main timeline. The container.swf file declares a variable named userName on its main timeline; the same script then loads another file called contents.swf into the target_mc movie clip:

// In container.swf:

_root.userName = "Tim";

target_mc.loadMovie("contents.swf");

my_btn.onRelease = function():Void {

trace(_root.userName);

};

In the following example, the loaded SWF file, contents.swf, also declares a variable named userName on its root timeline:

// In contents.swf:

_root.userName = "Mary";

After contents.swf loads into the movie clip in container.swf, the value of userName that's attached to the root timeline of the hosting SWF file (container.swf) would be set to "Mary" instead of "Tim". This could cause code in container.swf (as well as contents.swf) to malfunction.

To force _root to always evaluate to the timeline of the loaded SWF file, rather than the actual root timeline, use the _lockroot property. You can set this property either by the loading the SWF file or by the SWF file being loaded. When _lockroot is set to true on a movie clip instance, that movie clip acts as _root for any SWF file loaded into it. When _lockroot is set to true within a SWF file, that SWF file acts as its own root, no matter what other SWF file loads it. Any movie clip, and any number of movie clips, can set _lockroot to true. By default, this property is false.

For example, the author of container.swf could put the following code on Frame 1 of the main Timeline:

// Added to Frame 1 in container.swf:

target_mc._lockroot = true;

This step ensures that any references to _root in contents.swf--or any SWF file loaded into target_mc--refers to its own timeline, not to the actual root timeline of container.swf. Now when you click the button, "Tim" appears.

Alternatively, the author of contents.swf could add the following code to its main timeline:

// Added to Frame 1 in contents.swf:

this._lockroot = true;

This would ensure that no matter where contents.swf is loaded, any reference it makes to _root refers to its own main timeline, not to that of the hosting SWF file.

 

Loading image files into movie clips

TOP

You can use the loadMovie() function, or the MovieClip method of the same name, to load image files into a movie clip instance. You can also use the loadMovieNum() function to load an image file into a level.

When you load an image into a movie clip, the upper-left corner of the image is placed at the registration point of the movie clip. Because this registration point is often the center of the movie clip, the loaded image might not appear centered. Also, when you load an image to a root timeline, the upper-left corner of the image is placed on the upper-left corner of the Stage. The loaded image inherits rotation and scaling from the movie clip, but the original content of the movie clip is removed.

 

Changing movie clip position and appearance

TOP

To change the properties of a movie clip as it plays, write a statement that assigns a value to a property or use the setProperty() function. For example, the following code sets the rotation of instance mc to 45:

my_mc._rotation = 45;

This is equivalent to the following code, which uses the setProperty() function:

setProperty("my_mc", _rotation, 45);

Some properties, called read-only properties, have values that you can read but cannot set. (These properties are specified as read-only in their ActionScript 2.0 Language Reference entries.) The following are read-only properties: _currentframe, _droptarget, _framesloaded, _parent, _target, _totalframes, _url, _xmouse, and _ymouse.

You can write statements to set any property that is not read-only. The following statement sets the _alpha property of the wheel_mc movie clip instance, which is a child of the car_mc instance:

car_mc.wheel_mc._alpha = 50;

In addition, you can write statements that get the value of a movie clip property. For example, the following statement gets the value of the _xmouse property on the current level's timeline and sets the _x property of the my_mc instance to that value:

this.onEnterFrame = function() {

my_mc._x = _root._xmouse;

};

This is equivalent to the following code, which uses the getProperty() function:

this.onEnterFrame = function() {

my_mc._x = getProperty(_root, _xmouse);

};

The _x, _y, _rotation, _xscale, _yscale, _height, _width, _alpha, and _visible properties are affected by transformations on the movie clip's parent, and transform the movie clip and any of the clip's children. The _focusrect, _highquality, _quality, and _soundbuftime properties are global; they belong only to the level 0 main timeline. All other properties belong to each movie clip or loaded level.

 

Dragging movie clips

TOP

You can use the global startDrag() function or the MovieClip.startDrag() method to make a movie clip draggable. For example, you can make a draggable movie clip for games, drag-and-drop functions, customizable interfaces, scroll bars, and sliders.

A movie clip remains draggable until explicitly stopped by stopDrag() or until another movie clip is targeted with startDrag(). Only one movie clip at a time can be dragged in a SWF file.

To create more complicated drag-and-drop behavior, you can evaluate the _droptarget property of the movie clip being dragged. For example, you might examine the _droptarget property to see if the movie clip was dragged onto a specific movie clip (such as a "trash can" movie clip) and then trigger another action, as shown in the following example:

// Drag a piece of garbage.

garbage_mc.onPress = function() {

this.startDrag(false);

};

// When the garbage is dragged over the trashcan, make it invisible.

garbage_mc.onRelease = function() {

this.stopDrag();

// Convert the slash notation to dot notation using eval.

if (eval(this._droptarget) == trashcan_mc) {

garbage_mc._visible = false;

}

};

 

Creating an empty movie clip

TOP

To create a new, empty movie clip instance on the Stage, use the createEmptyMovieClip() method of the MovieClip class. This method creates a movie clip as a child of the clip that calls the method. The registration point for a newly created empty movie clip is the upper-left corner.

For example, the following code creates a new child movie clip named new_mc at a depth of 10 in the movie clip named parent_mc:

parent_mc.createEmptyMovieClip("new_mc", 10);

The following code creates a new movie clip named canvas_mc on the root timeline of the SWF file in which the script is run, and then activates loadMovie() to load an external JPEG file into itself:

this.createEmptyMovieClip("canvas_mc", 10);

canvas_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

As shown in the following example, you can load the image2.jpg image into a movie clip and use the MovieClip.onPress() method to make the image act like a button. Loading an image using loadMovie() replaces the movie clip with the image but doesn't give you access to movie clip methods. To get access to movie clip methods, you must create an empty parent movie clip and a container child movie clip. Load the image into the container and place the event handler on the parent movie clip.

// Creates a parent movie clip to hold the container.

this.createEmptyMovieClip("my_mc", 0);

// Creates a child movie clip inside of "my_mc".

// This is the movie clip the image will replace.

my_mc.createEmptyMovieClip("container_mc",99);

// Use MovieClipLoader to load the image.

var my_mcl:MovieClipLoader = new MovieClipLoader();

my_mcl.loadClip("http://www.helpexamples.com/flash/images/image2.jpg", my_mc.container_mc);

// Put event handler on the my_mc parent movie clip.

my_mc.onPress = function():Void {

trace("It works");

};

 

Duplicating or removing a movie cli0p

TOP

To duplicate or remove movie clip instances, use the duplicateMovieClip() or removeMovieClip() global functions, or the MovieClip class methods of the same name. The duplicateMovieClip() method creates a new instance of an existing movie clip instance, assigns it a new instance name, and gives it a depth, or z-order. A duplicated movie clip always starts at Frame 1, even if the original movie clip was on another frame when duplicated and is always in front of all previously defined movie clips placed on the timeline.

To delete a movie clip you created with duplicateMovieClip(), use removeMovieClip(). Duplicated movie clips are also removed if the parent movie clip is deleted.

 

Attaching a movie clip symbol to the Stage

TOP

The last way to create movie clip instances at runtime is to use the attachMovie() method. The attachMovie() method attaches to the Stage an instance of a movie clip symbol in the SWF file's library. The new clip becomes a child clip of the clip that attached it.

To use ActionScript to attach a movie clip symbol from the library, you must export the symbol for ActionScript and assign it a unique linkage identifier. To do this, you use the Linkage Properties dialog box.

By default, all movie clips that are exported for use with ActionScript load before the first frame of the SWF file that contains them. This can create a delay before the first frame plays. When you assign a linkage identifier to an element, you can also specify whether this content should be added before the first frame. If it isn't added in the first frame, you must include an instance of it in some other frame of the SWF file; if you don't, the element is not exported to the SWF file.

To assign a linkage identifier to a movie clip:

  1. Select Window > Library to open the Library panel.

  2. Select a movie clip in the Library panel.

  3. In the Library panel, select Linkage from the Library panel pop-up menu.

    The Linkage Properties dialog box appears.

  4. For Linkage, select Export for ActionScript.

  5. For Identifier, enter an ID for the movie clip.

    By default, the identifier is the same as the symbol name.

    You can optionally assign an ActionScript class to the movie clip symbol. This lets the movie clip inherit the methods and properties of a specified class.

  6. If you don't want the movie clip to load before the first frame, deselect the Export in First Frame option.

    If you deselect this option, place an instance of the movie clip on the frame of the timeline where you want it to be available. For example, if the script you're writing doesn't reference the movie clip until Frame 10, place an instance of the symbol at or before Frame 10 on the Timeline.

  7. Click OK.

After you've assigned a linkage identifier to a movie clip, you can attach an instance of the symbol to the Stage at runtime by using attachMovie().

To attach a movie clip to another movie clip:

  1. Assign a linkage identifier to a movie clip library symbol, as described in the previous example.

  2. With the Actions panel open (Window > Actions), select a frame in the Timeline.

  3. In the Actions panel's Script pane, type the name of the movie clip or level to which you want to attach the new movie clip.

    For example, to attach the movie clip to the root timeline, type this.

  4. In the Actions toolbox (at the left of the Actions panel), select ActionScript 2.0 Classes > Movie > MovieClip > Methods, and select attachMovie().

  5. Using the code hints that appear as a guide, enter values for the following parameters:

    • For idName, specify the identifier you entered in the Linkage Properties dialog box.

    • For newName, enter an instance name for the attached clip so that you can target it.

    • For depth, enter the level at which the duplicate movie clip will be attached to the movie clip. Each attached movie clip has its own stacking order, with level 0 as the level of the originating movie clip. Attached movie clips are always on top of the original movie clip, as shown in the following example:

      this.attachMovie("calif_id", "california_mc", 10);

 

Adding parameters to dynamically created movie clips

TOP

When you use MovieClip.attachMovie() and MovieClip.duplicateMovie() to create or duplicate a movie clip dynamically, you can populate the movie clip with parameters from another object. The initObject parameter of attachMovie() and duplicateMovie() allows dynamically created movie clips to receive clip parameters.

To populate a dynamically created movie clip with parameters from a specified object:

Do one of the following:

  • Use the following syntax with attachMovie():

    myMovieClip.attachMovie(idName, newName, depth [, initObject]);

  • Use the following syntax with duplicateMovie():

    myMovieClip.duplicateMovie(idName, newName, depth [, initObject]);

The initObject parameter specifies the name of the object whose parameters you want to use to populate the dynamically created movie clip.

To populate a movie clip with parameters by using attachMovie():

  1. In a new Flash document, create a movie clip symbol by selecting Insert > New Symbol.

  2. Type dynamic_mc in the Symbol Name text box, and select the Movie Clip behavior.

  3. Inside the symbol, create a dynamic text field on the Stage with an instance name of name_txt.

    Make sure this text field is below and to the right of the registration point.

  4. Select Frame 1 of the movie clip's Timeline, and open the Actions panel (Window > Actions).

  5. Create a new variable called name_str, and assign its value to the text property of name_txt, as shown in the following example:

    var name_str:String;

    name_txt.text = name_str;

  6. Select Edit > Edit Document to return to the main Timeline.

  7. Select the movie clip symbol in the library, and select Linkage from the Library pop-up menu.

    The Linkage Properties dialog box appears.

  8. Select the Export for ActionScript option, and Export in first frame.

  9. Type dynamic_id into the Indentifier text box, and click OK.

  10. Select the first frame of the main Timeline, and add the following code to the Actions panel's Script pane:

    /* Attaches a new movie clip and moves it to an x and y coordinate of 50 */

    this.attachMovie("dynamic_id", "newClip_mc", 99, {name_str:"Erick", _x:50, _y:50});

  11. Test the Flash document(Control > Test Movie).

    The name you specified in the attachMovie() call appears inside the new movie clip's text field.

 

Determining the next highest available depth

TOP

Mo determine the next highest available depth within a movie clip, use MovieClip.getNextHighestDepth(). The integer value returned by this method indicates the next available depth that will render in front of all other objects in the movie clip.

The following code attaches a new movie clip, with a depth value of 10, on the root timeline named file_mc. It then determines the next highest available depth in that same movie clip and creates a new movie clip called edit_mc at that depth.

this.attachMovie("menuClip","file_mc", 10, {_x:0, _y:0});

trace(file_mc.getDepth()); // 10

var nextDepth:Number = this.getNextHighestDepth();

this.attachMovie("menuClip", "edit_mc", nextDepth, {_x:200, _y:0});

trace(edit_mc.getDepth()); // 11

In this case, the variable named nextDepth contains the value 11 because that's the next highest available depth for the edit_mc movie clip.

Do not use MovieClip.getNextHighestDepth() with components; instead, use the depth manager.

 

Determining the instance at a particular depth

TOP

To determine the instance at a particular depth, use MovieClip.getInstanceAtDepth(). This method returns a reference to the MovieClip instance at the specified depth.

The following code combines getNextHighestDepth() and getInstanceAtDepth() to determine the movie clip at the (current) highest occupied depth on the root timeline.

var highestOccupiedDepth:Number = this.getNextHighestDepth() - 1;

var instanceAtHighestDepth:MovieClip = this.getInstanceAtDepth(highestOccupiedDepth);

 

Determining the depth of an instance

TOP

To determine the depth of a movie clip instance, use MovieClip.getDepth().

The following code iterates over all the movie clips on a SWF file's main timeline and shows each clip's instance name and depth value in the Output panel:

for (var item:String in _root) {

var obj:Object = _root[item];

if (obj instanceof MovieClip) {

var objDepth:Number = obj.getDepth();

trace(obj._name + ":" + objDepth)

}

}

 

Swapping movie clip depths

TOP

To swap the depths of two movie clips on the same timeline, use MovieClip.swapDepths(). The following examples show how two movie clip instances can swap depths at runtime.

To swap movie clip depths:

  1. Create a new Flash document called swap.fla.

  2. Draw a blue circle on the Stage.

  3. Select the blue circle, and then select Modify > Convert to Symbol.

  4. Select the Movie clip option, and then click OK.

  5. Select the instance on the Stage, and then type first_mc into the Instance Name text box in the Property inspector.

  6. Draw a red circle on the Stage, and then select Modify > Convert to Symbol.

  7. Select the Movie clip option, and then click OK.

  8. Select the instance on the Stage, and then type second_mc into the Instance Name text box in the Property inspector.

  9. Drag the two instances so that they overlap slightly on the Stage.

  10. Select Frame 1 of the Timeline, and then type the following code into the Actions panel:

    first_mc.onRelease = function() {

    this.swapDepths(second_mc);

    };

    second_mc.onRelease = function() {

    this.swapDepths(first_mc);

    };

  11. Select Control > Test Movie to test the document.

    When you click the instances on the Stage, they swap depths. You'll see the two instances change which clip is on top of the other clip.

 

When to enable caching

TOP

Enabling caching for a movie clip creates a surface, which has several advantages, such as helping complex vector animations to render fast. There are several scenarios in which you will want to enable caching. It might seem as though you will always want to enable caching to improve the performance of your SWF files; however, there are situations in which enabling caching does not improve performance, or even decrease it. This section describes scenarios in which caching should be used, and when to use regular movie clips.

Overall performance of cached data depends on how complex the vector data of your instances are, how much of the data you change, and whether or not you set the opaqueBackground property. If you are changing small regions, the difference between using a surface and using vector data could be negligible. You might want to test both scenarios with your work before you deploy the application.

When to use bitmap caching

The following are typical scenarios in which you might see significant benefits when you enable bitmap caching.

Complex background image  An application that contains a detailed and complex background image of vector data (perhaps an image where you applied the trace bitmap command, or artwork that you created in Adobe Illustrator). You might animate characters over the background, which slows the animation because the background needs to continuously regenerate the vector data. To improve performance, you can select the content, store it in a movie clip, and set the opaqueBackground property to true. The background is rendered as a bitmap and can be redrawn quickly, so that your animation plays much faster.

Scrolling text field  An application that displays a large amount of text in a scrolling text field. You can place the text field in a movie clip that you set as scrollable with scrolling bounds (the scrollRect property). This enables fast pixel scrolling for the specified instance. When a user scrolls the movie clip instance, Flash shifts the scrolled pixels up and generates the newly exposed region instead of regenerating the entire text field.

Windowing system  An application with a complex system of overlapping windows. Each window can be open or closed (for example, web browser windows). If you mark each window as a surface (set the cacheAsBitmap property to true), each window is isolated and cached. Users can drag the windows so that they overlap each other, and each window doesn't need to regenerate the vector content.

All of these scenarios improve the responsiveness and interactivity of the application by optimizing the vector graphics.

You can find a sample source file that shows you how bitmap caching can be applied to an instance. Find the file called cacheBitmap.fla, in the Samples folder on your hard disk.

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap.

You can also find a sample source file that shows you how to apply bitmap caching to scrolling text. Find the sample source file, flashtype.fla, in the Samples folder on your hard disk.

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType.

When to avoid using bitmap caching

Misusing this feature could negatively affect your SWF file. When you develop a FLA file that uses surfaces, remember the following guidelines:

  • Do not overuse surfaces (movie clips with caching enabled). Each surface uses more memory than a regular movie clip, which means that you should only enable surfaces when you need to improve rendering performance.

    A cached bitmap can use significantly more memory than a regular movie clip instance. For example, if the movie clip on Stage is 250 pixels by 250 pixels in size, when cached it might use 250 KB instead of 1 KB when it's a regular (uncached) movie clip instance.

  • Avoid zooming into cached surfaces. If you overuse bitmap caching, a large amount of memory is consumed (see previous bullet), especially if you zoom in on the content.

  • Use surfaces for movie clip instances that are largely static (nonanimating). You can drag or move the instance, but the contents of the instance should not animate or change a lot. For example, if you rotate or transform an instance, the instance changes between the surface and vector data, which is difficult to process and negatively affects your SWF file.

  • If you mix surfaces with vector data, it increases the amount of processing that Flash Player (and sometimes the computer) needs to do. Group surfaces together as much as possible; for example, when you create windowing applications.

Caching a movie clip

TOP

To cache a movie clip instance, you need to set the cacheAsBitmap property to true. After you set the cacheAsBitmap property to true, you might notice that the movie clip instance automatically pixel-snaps to whole coordinates. When you test the SWF file, you should notice that any complex vector animation renders much faster.

A surface (cached bitmap) is not created, even if cacheAsBitmap is set to true, if one or more of the following occurs:

  • The bitmap is greater than 2880 pixels in height or width.

  • The bitmap fails to allocate (out of memory error).

To cache a movie clip:

  1. Create a new Flash document, and name the file cachebitmap.fla.

  2. Type 24 into the fps text box in the Property inspector (Window > Properties > Properties).

  3. Create or import a complex vector graphic into the FLA file.

    You can find a complex vector graphic in the finished source file for this example in the following directory:

    • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.

    • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap.

  4. Select the vector graphic, and select Modify > Convert to Symbol.

  5. Type star into the Name text box, and then click Advanced (if the dialog box is not already expanded).

  6. Select Export for ActionScript (which also selects Export in first frame).

  7. Type star_id into the Identifier text box.

  8. Click OK to create the movie clip symbol, with the linkage identifier of Star.

  9. Select Frame 1 of the Timeline, and then add the following ActionScript to the Actions panel:

    import mx.transitions.Tween;

    var star_array:Array = new Array();

    for (var i:Number = 0; i < 20; i++) {

    makeStar();

    }

    function makeStar():Void {

    var depth:Number = this.getNextHighestDepth();

    var star_mc:MovieClip = this.attachMovie("star_id", "star" + depth, depth);

    star_mc.onEnterFrame = function() {

    star_mc._rotation += 5;

    }

    star_mc._y = Math.round(Math.random() * Stage.height - star_mc._height / 2);

    var star_tween:Tween = new Tween(star_mc, "_x", null, 0, Stage.width, (Math.random() * 5) + 5, true);

    star_tween.onMotionFinished = function():Void {

    star_tween.yoyo();

    };

    star_array.push(star_mc);

    }

    var mouseListener:Object = new Object();

    mouseListener.onMouseDown = function():Void {

    var star_mc:MovieClip;

    for (var i:Number = 0; i < star_array.length; i++) {

    star_mc = star_array[i];

    star_mc.cacheAsBitmap = !star_mc.cacheAsBitmap;

    }

    }

    Mouse.addListener(mouseListener);

  10. Select Control > Test Movie to test the document.

  11. Click anywhere on the Stage to enable bitmap caching.

    You'll notice that the animation changes from appearing to animate at 1 frame per second, to a smooth animation where the instances animate back and forth across the Stage. When you click the Stage, it toggles the cacheAsBitmap setting between true and false.

 

Setting the background of a movie clip

TOP

You can set an opaque background for a movie clip. For example, when you have a background that contains complex vector art, you can set the opaqueBackground property to a specified color (typically the same color as the Stage). The background is then treated as a bitmap, which helps optimize performance.

When you set cacheAsBitmap to true, and also set the opaqueBackground property to a specified color, the opaqueBackground property allows the internal bitmap to be opaque and rendered faster. If you do not set cacheAsBitmap to true, the opaqueBackground property adds an opaque vector-square shape to the background of the movie clip instance. It does not create a bitmap automatically.

The following example shows how to set the background of a movie clip to optimize performance.

To set the background of a movie clip:

  1. Create a new Flash document called background.fla.

  2. Draw a blue circle on the Stage.

  3. Select the blue circle, and then select Modify > Convert to Symbol.

  4. Select the Movie clip option, and then click OK.

  5. Select the instance on the Stage, and then type my_mc into the Instance Name text box in the Property inspector.

  6. Select Frame 1 of the Timeline, and then type the following code into the Actions panel:

    /* When you set cacheAsBitmap, the internal bitmap is opaque and renders faster. */

    my_mc.cacheAsBitmap = true;

    my_mc.opaqueBackground = 0xFF0000;

  7. Select Control > Test Movie to test the document.

    The movie clip appears on the Stage with the background color that you specified.

 

Using movie clips as masks

TOP

You can use a movie clip as a mask to create a hole through which the contents of another movie clip are visible. The mask movie clip plays all the frames in its timeline, the same as a regular movie clip. You can make the mask movie clip draggable, animate it along a motion guide, use separate shapes within a single mask, or resize a mask dynamically. You can also use ActionScript to turn a mask on and off.

You cannot use a mask to mask another mask. You cannot set the _alpha property of a mask movie clip. Only fills are used in a movie clip that is used as a mask; strokes are ignored.

To create a mask:

  1. Create a square on the Stage with the Rectangle tool.

  2. Select the square and press F8 to convert it into a movie clip.

    This instance is your mask.

  3. In the Property inspector, type mask_mc in the Instance Name text box.

    The masked movie clip is revealed under all opaque (nontransparent) areas of the movie clip acting as the mask.

  4. Select Frame 1 in the Timeline.

  5. Open the Actions panel (Window > Actions) if it isn't already open.

  6. In the Actions panel, enter the following code:

    System.security.allowDomain("http://www.helpexamples.com");

    this.createEmptyMovieClip("img_mc", 10);

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip):Void {

    target_mc.setMask(mask_mc);

    }

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    my_mcl.addListener(mclListener);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

  7. Select Control > Test Movie to test the document.

    An external JPEG image loads into the SWF file at runtime, and is masked by the shape you drew previously on the Stage.

 

About masking device fonts

TOP

You can use a movie clip to mask text that is set in a device font. In order for a movie clip mask on a device font to work properly, the user must have Flash Player 6 (6.0.40.0) or later.

When you use a movie clip to mask text set in a device font, the rectangular bounding box of the mask is used as the masking shape. That is, if you create a nonrectangular movie clip mask for device font text in the Flash authoring environment, the mask that appears in the SWF file is the shape of the rectangular bounding box of the mask, not the shape of the mask itself.

You can mask device fonts only by using a movie clip as a mask. You cannot mask device fonts by using a mask layer on the Stage.

 

About alpha channel masking

TOP

Alpha channel masking is supported if both the mask and the maskee movie clips use bitmap caching. This support also lets you use a filter on the mask independently of the filter that is applied to the maskee itself.

In this sample file, the mask is an oval (oval_mask) that has alpha of 50% and a blur filter applied to it. The maskee (flower_maskee) has alpha of 100% and no filter applied on it. Both movie clips have runtime bitmap caching applied in the Property inspector.

In the Actions panel, the following code is placed on Frame 1 of the Timeline:
flower_maskee.setMask(oval_mask);

When you test the document (Control > Test Movie), the maskee is alpha blended by using the mask.

NOTE : Mask layers do not support alpha channel masking. You must use ActionScript code to apply a mask, and use runtime bitmap caching.

Assigning a class to a movie clip symbol

TOP

Using ActionScript 2.0, you can create a class that extends the behavior of the built-in MovieClip class and then use the Linkage Properties dialog box to assign that class to a movie clip library symbol. Whenever you create an instance of the movie clip to which the class is assigned, it assumes the properties and behaviors defined by the class assigned to it.

In a subclass of the MovieClip class, you can provide method definitions for the built-in MovieClip methods and event handlers, such as onEnterFrame and onRelease. In the following procedure, you'll create a class called MoveRight that extends the MovieClip class; MoveRight defines an onPress handler that moves the clip 20 pixels to the right whenever the user clicks the movie clip. In the second procedure, you'll create a movie clip symbol in a new Flash (FLA) document and assign the MoveRight class to that symbol.

To create a movie clip subclass:

  1. Create a new directory called BallTest.

  2. Select File > New, and select ActionScript file from the list of document types to create a new ActionScript file.

  3. Enter the following code in your script file:

    // MoveRight class -- moves clip to the right 20 pixels when clicked

    class MoveRight extends MovieClip {

    public function onPress() {

    this._x += 20;

    }

    }

  4. Save the document as MoveRight.as in the BallTest directory.

To assign the class to a movie clip symbol:

  1. In Flash, select File > New, select Flash Document from the list of file types, and click OK.

  2. Using the Oval tool, draw a circle on the Stage.

  3. Select the circle, and select Modify > Convert to Symbol.

  4. In the Convert to Symbol dialog box, select Movie Clip as the symbol's behavior, and enter ball_mc in the Name text box.

  5. Select Advanced to show the options for Linkage, if they aren't already showing.

  6. Select the Export for ActionScript option, and type MoveRight in the Class text box. Click OK.

  7. Save the file as ball.fla in the BallTest directory (the same directory that contains the MoveRight.as file).

  8. Test the Flash document(Control > Test Movie).

    Each time you click the ball movie clip, it moves 20 pixels to the right.

If you create component properties for a class and want a movie clip to inherit those component properties, you need to take an additional step: with the movie clip symbol selected in the Library panel, select Component Definition from the Library pop-up menu and enter the new class name in the Class box.

 

Controlling member access in your classes

TOP

In the example presented in the second procedure under Assigning a class to a movie clip symbol, you added the instance of the Ball symbol to the Stage while authoring. As discussed in Adding parameters to dynamically created movie clips, you can assign parameters to clips you create at runtime by using the initObject parameter of attachMovie() and duplicateMovie(). You can use this feature to initialize properties of the class you're assigning to a movie clip.

To pass arguments to a custom c

// Distance property determines how many

// pixels to move clip for each mouse press.

var distance:Number;

function onPress() {

this._x += this.distance;

}

}

  • Save your progress.

  • Create a new Flash document, and save it as MoveRightDistance.fla in the same directory as the class file.

  • Create a movie clip symbol that contains a vector shape, such as an oval, and then delete any content from the Stage.

    You only need a movie clip symbol in the library for this example.

  • In the Library panel, right-click (Windows) or Control-click (Macintosh) the symbol and select Linkage from the context menu.

  • Assign the linkage identifier Ball to the symbol.

  • Type MoveRightDistance into the AS 2.0 Class text box.

  • Add the following code to Frame 1 of the Timeline:

    this.attachMovie("Ball", "ball50_mc", 10, {distance:50});

    this.attachMovie("Ball", "ball125_mc", 20, {distance:125});

    This code creates two new instances of the symbol on the root timeline of the SWF file. The first instance, named ball50_mc, moves 50 pixels each time it is clicked; the second, named ball125_mc, moves 125 pixels each time it is clicked.

  • Select Control > Test Movie to test the SWF file.

  • 10

    Copyright ADOBE - All Rights Reserved Worldwide

     

     

    More Topics:

    Working with Flash Documents

    How to work in Flash WorkSpace

    Working with Projects in Flash

    Process to Build your First Application in Flash

    Using Symbols, Instances and Library Assets in Flash

    How to Build Video Player in Flash

    How to Work with Color, Strokes and Fills in Flash

    How to Create Document in Flash

    What is Vector and Bitmap Graphics in Flash

    How to Create a Banner in Flash, Part 1

    How to Work with Text in Flash

    How to Create a Banner in Flash, Part 2

    How to Use Imported Artwork in Flash

    How to Create a Banner in Flash, Part 3

    How to Work with Graphic Objects in Flash

    How to Work with Layers in Flash

    How to Use Filters and Blends

    Working with Graphics in Flash

    What is Accessibility Features in Flash

    How to Create Motion (Shape Tween & Motion Tween) in Flash

    How to Create an Application in Flash

    What is Masking in Flash

    How to Work with Video in Flash

    How to Use Layout Tools in Flash

    What are Behaviors in Flash

    How to Work with Sound in Flash

    How to Create Symbols and Instances in Flash

    What is ActionScript in Flash

    How to Write ActionScript With Script Assist in Flash

    How to Add Button Animation and Navigation in Flash

    What is Data Integration in Flash

    How to Work with Screens

    How to Create a Presentation with Screens

    What is Extending Flash

    How to Create Multilanguage Text in Flash

    How to Create Graphics: Draw in Flash

    What is Flash Lite

    Ways of Data Integration

    How to Create Graphics: Create a Timeline Animation in Flash

    Getting Started with Flash Lite in Flash

    How to Publish Flash Documents

    How to Create Graphics: Making Animations with Easing

    Learning Flash Lite 1.X ActionScript in Flash

    How to Export Flash Content and Images from Flash

    How to Create Graphics: Applying Gradients in Flash

    Process of Writing and Editing ActionScript 2.0 in Flash

    How to Create Accessible Content in Flash

    How to Create Graphics: Apply Graphic Filters and Blends

    What is Data and Data Types in Flash

    Process of Printing from SWF Files in Flash

    Using ActionScript: How to Use Script Assist mode in Flash

    Learn Syntax and Language Fundamentals in Flash

    How to Create E-learning Content in Flash

    Using ActionScript: How to Write Scripts in Flash

    Working with Functions and Methods in Flash

    Process of Using Templates in Flash

    Using ActionScript: Process of Adding Interactivity in Flash

    What are Classes in Flash

    Control Tag Summary of XML to UI in Flash

    Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

    What is Inheritance in Flash

    What is Data Integration: Overview

    Using ActionScript: How to Work with Objects and Classes in Flash

    Overview on Interfaces in Flash

    What is Data Integration: Using XML for a Timesheet

    How to Work with Text and Strings in Flash

    How to use Handling Events in Flash

    What is Data Integration: Using XUpdate to Update the Timesheet

    Learning Animation, Filters and Drawings in Flash

    How to Work with Movie Clips in Flash

    How to Create Interaction with ActionScript in Flash

    How to Work with Images, Sound, and Video in Flash

    How to Work with External Data in Flash

    What is Security in Flash

    How to Debug Applications in Flash

    List of Error Messages in Flash

    Using Object-Oriented Programming with ActionScript 1.0 in Flash

    How to Write Scripts for Earlier Versions of Flash Player in Flash

    List of all Keyboard Keys and Key Code Values for using in Flash

    Terminology

    Introduction to Components in Flash

    What are Components in Flash

    How to Create an Application with Components

    How to Work with Components in Flash

    How to Handle Component Events in Flash

    How to Customize Components in Flash

    How to Create Components in Flash

    What is Collection Properties in Flash