Making Movie Clips Perform in Flash MX - Creating Instances
(Page 4 of 4 )
There are four ways to create a new movie clip instance. Three of these are programmatic; the other is strictly manual and is undertaken in the Flash authoring tool. All but one method, createEmptyMovieClip(), require an existing movie clip symbol from which to derive the new instance.
Manually creating instances
We can create movie clip instances manually using the Library in the Flash authoring environment. By physically dragging a movie clip symbol out of the Library and onto the Stage, we generate a new instance. An instance created in this way should be named manually via the Instance panel (Flash 5) or Property inspector (Flash MX). You’ll learn more about instance names later in this chapter. Refer to “Using Symbols, Instances, and Library Assets” in the Macromedia Flash Help if you’ve never worked with movie clips in Flash.
Creating instances with duplicateMovieClip( ) Any instance that already resides on the Stage of a Flash movie can be duplicated with ActionScript. We can then treat that copy as a completely independent clip. Both manually created and programmatically created clip instances can be duplicated. In other words, it’s legal to duplicate a duplicate.
There are two ways to duplicate an instance using duplicateMovieClip():
When created using the duplicateMovieClip( ) function, the newly created clip is attached as a child of eithertarget’s ortheClip ’s parent. That is, the new clip becomes a sibling of eithertarget ormyClip in the movie clip hierarchy.
When created via duplicateMovieClip(), an instance is initially positioned directly on top of its seed clip. Our first post-duplication task, therefore, is usually moving the duplicated clip to a new position. For example:
ball_mc.duplicateMovieClip("ball2_mc", 0);
ball2_mc._x += 100;
ball2_mc._y += 50;
Duplicated instances whose seed clips have been transformed (e.g., colored, rotated, or resized), via ActionScript or manually in the Flash authoring tool, inherit the transformation of their seed clips at duplication time. Subsequent transformations to the seed clip do not affect duplicated instances. Likewise, each instance can be transformed separately. For example, if a seed clip is rotated 45 degrees and then duplicated, the duplicate instance’s initial rotation is 45 degrees:
seedClip_mc._rotation = 45;
seedClip_mc.duplicateMovieClip("newClip_mc", 0);
trace(newClip_mc._rotation); // Displays: 45
If we then rotate the duplicate instance by 10 degrees, its rotation is 55 degrees, but the seed clip’s rotation is still 45 degrees:
newClip_mc._rotation += 10;
trace(newClip_mc._rotation); // Displays: 55
trace(seedClip_mc._rotation); // Displays: 45
By duplicating many instances in a row and adjusting the transformation of each duplicate slightly, we can achieve interesting compound effects, such as stars in the sky, trails effects, and geometric animations (for an example, see “Load Event Starfield” in the online Code Depot).
Using duplicateMovieClip() offers other advantages over placing clips manually in a movie, such as the ability to:
- Control exactly when a clip appears on the Stage, relative to a program’s execution
- Control exactly when a clip is removed from the Stage, relative to a program’s execution
- Copy a clip’s event handlers
These abilities give us advanced programmatic control over the content in a movie. With a manually created clip, we must preordain the birth and death of the clip using the timeline.
Creating instances with attachMovie() Like duplicateMovieClip(), the attachMovie() method lets us create a movie clip instance at runtime; however, attachMovie() creates a new instance from a Library symbol instead of from another movie clip instance. To “attach” a movie clip means to make one movie clip the child of either the main timeline or another movie clip in the movie clip hierarchy. In order to use attachMovie() to create an instance of a symbol, we must first export that symbol from the Library. Here’s how:
- In the Library, select the desired symbol.
- In the Library’s pop-up Options menu, select Linkage. The Linkage Properties dialog box appears.
- Select the Export For ActionScript checkbox.
- In the Identifier field, type a unique name for the clip symbol. The name can be any string—often simply the same name as the symbol itself—but should be different from all other exported clip symbols.
- In Flash MX, we can also set the frame at which the link clip will be exported with the movie. For details, see MovieClip.attachMovie() in the Language Reference.
- Click OK.
Once a clip symbol has been exported, we can attach new instances of that symbol to an existing clip by invoking attachMovie() with the following syntax:
theClip.attachMovie(symbolIdentifier, newName, depth, [initObject]);
wheretheClip is the name of the movie clip to which we want to attach the new instance. IftheClip is omitted, attachMovie() attaches the new instance to the current clip (the clip on which the attachMovie() statement resides). ThesymbolIdentifier parameter is a string containing the name of the symbol we’re using to generate our instance, as specified in the Identifier field of the Linkage options in the Library (Step 4). ThesymbolIdentifier is not necessarily the same name as the symbol itself. ThenewName parameter is a string that specifies the identifier for the new instance we’re creating. IfnewName is not a string that converts to a legal identifier, you’re in for some potentially surprising results, as shown in the examples later in this section. Finally,depth is an integer that designates where in the host clip’s content stack to place the new instance. Flash MX adds support for a fourth, optional parameter calledinitObject, which lets you copy properties from an existing object to the new clip. See MovieClip.attachMovie() in the Language Reference for full details.
For example, to attach a new movie clip, based on the “square” symbol, to the current timeline, use:
this.attachMovie("square", "square1_mc", 1);
square1_mc._x = 50; // Position the new clip at a horizontal position of 50
square1_mc._y = 200; // ...and a vertical position of 200
The attachMovie() method attaches the new clip as a child oftheClip (or of the current clip if no clip is specified). Contrast this with duplicateMovieClip(), which attaches the clip as a sibling of the duplicated clip.
When we attach an instance to another clip, the instance is positioned in the center of the clip, among the clip’s content stack. When we attach an instance to the main movie of a document, the instance is positioned in the upper-left corner of the Stage, at coordinates (0, 0).
In Flash Player 6, the attachMovie() function returns a reference to the newly created movie clip, which is useful for debugging. If the function returnsundefined, then the movie clip creation failed (except in Flash 5, where attachMovie() always returnsundefined). In this case, you most likely specified the wrong name forsymbolIdentifier (remember to specify the quotes around the string, enter the name correctly, and use the export name specified in the Linkage options, not the symbol’s Library name). ThesymbolIdentifier string is not case-sensitive, so if the symbol is exported as “Symbol 1”, you can (but should not, as a matter of good form) specify “symbol 1” assymbolIdentifier.
The return value of the attachMovie() function is particularly useful if the operation succeeds and yet you are still having trouble referring to your newly created movie clip by the expected identifier. Technically,newName does not need to be a legal identifier, but you’ll have trouble referring to the new clip if it isn’t, unless you store the return value in a variable. That is, you can use the return value to access the clip after it is attached, if thenewName parameter was specified incorrectly and could not be converted to a legal identifier. ThenewName parameter is actually converted first to a string, and later converted again to an identifier. Let’s see how this works.
In our first example,newName is specified as “newClip 1”, which has a space in it, so it can’t be converted to a legal identifier. Luckily, you can use the return value stored innewClip_mcto refer to the newly created clip:
newClip_mc = _root.attachMovie("Symbol 1", "newClip 1", 0);
trace(newClip_mc); // Displays: _level0.newClip 1
// (which is not a valid identifier)
In the next example,newName is specified asnewClip1, which takes the form of a legal identifier but is missing the necessary quotes to make it a string. The attachMovie() command first tries to convert it to a string, but becausenewClip1looks to the interpreter like anundefinedvariable, the conversion yields the empty string. Luckily, you can again use the return value stored innewClip_mcto refer to the newly created clip:
newClip_mc = _root.attachMovie("Symbol 1", newClip1, 0);
trace(newClip_mc); // Displays _level0.
// (the clip's name is an empty string!)
What ifnewName is specified as a legal identifier, such asball_mc, that already refers to an existing movie clip? Again, the attachMovie() command first tries to convert it to a string, which (referring to Table 3-2 for string conversion of movie clips) yields the interim string “_level0.ball_mc” fornewName. This series of conversions results in the newly created movie clip having the incorrect name “_level0._level0.ball_mc”. Luckily, yet again you can use the return value stored innewClip_mcto refer to the newly created clip properly:
//Assume ball_mc is an existing (valid) movie clip identifier
newClip_mc = _root.attachMovie("Symbol 1", ball_mc, 0);
trace(newClip_mc); // Displays "_level0._level0.ball_mc"
As you can see, life is much easier when we make sure to provide a string that converts to a legal identifier fornewName.
Creating instances with createEmptyMovieClip() As of Flash Player 6, completely blank new movie clip instances can be created in an existing clip with the createEmptyMovieClip( ) method, which has the following syntax:
theClip.createEmptyMovieClip(newName, depth);
wheretheClip is the name of an existing movie clip to which we want to attach a new, empty movie clip. The new clip instance is given a name ofnewName and placed intheClip’s content stack at the specifieddepth.
Movie clips created with createEmptyMovieClip() are not derived from a Library symbol; they are simply blank movie clip instances with one frame. Empty movie clips can be used as drawing canvases, script clips, or containers for nested clips (e.g., a form clip that contains text fields and a Submit button).
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter 13 of the book ActionScript for Flash MX: the Definitive Guide, second edition, written by Colin Moock (O'Reilly; ISBN: 059600396X). Check it out today at your favorite bookstore. Buy this book now.
|
|