Manipulating Movie Clips


Several properties of movie clips, such as color and alpha, can be manipulated to change the appearance of the movie clips. Other properties can be used to move the movie clip across the stage. There are even several properties of movie clips that control the visual aspects of the object, such as blend modes and filters.

Following is a short list of those properties with descriptions:

  • _x The horizontal position of a movie clip on the stage.

  • _y The vertical position of a movie clip on the stage.

  • _xscale The horizontal scale of a movie clip represented as a percentage; greater than 100% enlarges the clip, less than 100% shrinks the clip.

  • _yscale The vertical scale of a movie clip represented as a percentage; greater than 100% enlarges the clip, less than 100% shrinks the clip.

  • _height The height of a movie clip in pixels.

  • _width The width of a movie clip in pixels.

  • _alpha The transparent level of a movie clip from 0 to 100.

  • _rotation The rotation of a movie clip in degrees.

  • _visible A Boolean value representing whether a movie clip is visible (true) or not (false).

Now that you have a list of some of the basic visual properties of movie clips, we can begin using them to animate movie clips.

Animating Movie Clips with ActionScript

Animating movie clips with ActionScript has many benefits that manually animating them does not; file size reduction is one of the major benefits.

When you create tweens, such as in Chapters 4 and 5, you are requiring Flash to not only create the necessary animation between the two points, but to also remember it when the .swf file is compiled. This causes the file size to increase. Even if you use keyframe animation without any tweening, the file size will increase with each keyframe. Using ActionScript to control the movement of movie clips is an easy way to trim file size because Flash has to remember only the original position of the movie clip, and then ActionScript will execute the movement at runtime.

Here is a basic example of scripted movement:

1.

Create a new Flash document.

2.

Draw a small circle on the left side of the stage about 50 pixels wide.

3.

Select the drawn circle (including the circle's stroke) and convert it to a symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of circleMC and choose Movie Clip as the behavior.

5.

Give the circle on the stage an instance name of circle_mc.

6.

Create a new layer and name it actions.

7.

In the first frame of the Actions layer, open the Actions panel and place these actions within it:

 //this event will make the circle move this.onEnterFrame = function(){      //move the circle 5 pixels at a time      circle_mc._x += 5; } 

You used the onEnterFrame event, which will continually trigger throughout the entire run of the movie at the same pace as the frames per second (fps). Within the onEnterFrame event, you are moving the circle_mc movie clip by 5 pixels each time the event fires.

8.

Now test the movie and see the circle moving across the screen as shown in Figure 13.2.

Figure 13.2. Using ActionScript, you can animate movie clips just as smoothly as using tweens, and the file size stays tiny.


That was a simple example of moving a movie clip from one side of the screen to the other, but the problem is that the circle_mc continues to move well past the end of the stage. So we will continue the example by adding a conditional statement to see if the circle_mc has moved far enough, and then it will stop moving. We are also adding a trace function, which we will discuss later.

Follow these steps to continue the example:

1.

Close the test movie screen and return to the authoring environment.

2.

In the first frame of the Actions layer, replace the actions in the Actions panel with these:

 //this event will make the circle move this.onEnterFrame = function(){      //this trace function lets us know it is working      trace("working");      //if it hasn't gone too far, move the circle 5 pixels      if(circle_mc._x < 550){           circle_mc._x += 5;      } } 

This code is taking the original code and placing a conditional statement to check whether circle_mc has passed 550 in its horizontal position (550 being the default width of the Flash stage). If it has not yet reached that point, the movie clip will continue moving to the right. Also, we put a TRace function in the code, which will be discussed in the next section.

3.

Now test the movie.

Notice that as before, the circle_mc movie clip moves across the screen, but this time, when it reaches a certain point it stops moving. Also, the TRace function continues to run even after the circle has stopped moving, as you can see in Figure 13.3. This is because even though the circle has stopped moving, the onEnterFrame event is still being triggered.

Figure 13.3. Even though the circle_mc movie clip has stopped moving, the trace function continues to work while the onEnterFrame event fires.


Even though it's hard to tell, the onEnterFrame event is taking up valuable processor power that can be taken back. In the next extension of this example, we will remove the onEnterFrame event and regain the processor power.

The final step in this example is to remove the onEnterFrame event when we no longer need it, and regain the processor power. To do this, we will use the delete statement in conjunction with our conditional statement.

Follow these steps:

1.

Close the test movie screen and return to the authoring environment.

2.

In the first frame of the actions layer, replace the actions in the Actions panel with these:

 //this event will make the circle move this.onEnterFrame = function(){      //this trace function lets us know it is working      trace("working");      //if it hasn't gone too far, move the circle 5 pixels      if(circle_mc._x < 550){           circle_mc._x += 5;      }else{           //destroy the onEnterFrame           delete this.onEnterFrame;      } } 

The changes were small; all we did was add an else statement to coincide with the if statement. When the circle_mc movie clip reaches the correct position, the else statement is triggered, the onEnterFrame event is destroyed, and the processor power is returned to other applications on the user's computer.

3.

Test the movie.

When the movie is tested, the circle_mc acts exactly the same way it has been acting, moving from the left side of the stage to the right side. This time, however, when the circle_mc reaches the horizontal position of 550 or greater, the circle_mc movie clip stops moving and the onEnterFrame event is deleted, thereby stopping the trace function from occurring.

Even though this example was a little boring, it is very powerful. We moved a movie clip from one side of the screen to the other, stopped, and then destroyed the action that was moving it in the first place.

We are going to take the basic fundamentals from the preceding example and do a more advanced example of a movie clip moving from spot to spot on the stage. We will use some basic math to make it slow down and speed up. But before we do that, you need to learn about another feature new to Flash that will help a great deal with complex animations.

The cacheAsBitmap Property

The cacheAsBitmap property of a movie clip works in much the same manner as the Use Runtime Bitmap Caching option in the Properties Inspector. When this property of a movie clip is set to true, it will increase performance with regard to animations, especially in X,Y coordinate changes.

You set it in ActionScript as you would any other property:

 myMovie.cacheAsBitmap = true; 

Now for most of the animations in this chapter, this property will not make a substantial difference in performance. But in a later example, when there are multiple movie clips all being animated, you should notice a performance increase, especially if you increase the number of objects being animated.

NOTE

If you were to set a filter to a movie clip with ActionScript, the cacheAsBitmap property will automatically be set to true.


Using Math to Help Animate Movie Clips

So far we have just moved a movie clip using a static number. Using math, you can improve the appearance of animating movie clips. You can make them appear to have a bouncy momentum. You can make them appear to be bound by gravity. You can even make them appear to be easing in and out each time they move, and that is what we are going to cover in this next example, which extends the preceding example.

1.

Close the test screen and return to the main timeline.

2.

In the first frame of the Actions layer, open the Actions panel and replace the code with this:

 //cache the circle for performance reasons circle_mc.cacheAsBitmap = true; //the easing control var friction:Number = 0.5; //the starting positions var currentX:Number = circle_mc._x; var currentY:Number = circle_mc._y; //set the boundaries var xBoundary:Number = 550; var yBoundary:Number = 400; //set some initial go to points var newX:Number = Math.floor(Math.random()*xBoundary); var newY:Number = Math.floor(Math.random()*yBoundary); 

These actions first set the cacheAsBitmap property to true and then declare some variables we will be using in the event later on in the code. The friction variable controls the speed of the movie clip as it eases in and out of position. The currentX and currentY variables hold the current position of our movie clip. The boundary variables are used in setting the next position. The newX and the newY variables use the Math object to choose new positions at random, based on the boundaries, for the movie clip to move to. Now let's add the code to do the actual moving.

3.

After the code is in the Actions panel, place this code:

 //this is the event for the motion this.onEnterFrame=function(){      //continually get the current position      currentX = Math.floor(circle_mc._x);      currentY = Math.floor(circle_mc._y);      //check the horizontal position      if(currentX != newX){           circle_mc._x += (newX-currentX)*friction;      }else{           newX = Math.floor(Math.random()*xBoundary);      }      //do the same with the horizontal position      if(currentY != newY){           circle_mc._y += (newY-currentY)*friction;      }else{           newY = Math.floor(Math.random()*yBoundary);      } } 

This code constantly checks the current position of the movie clip and stores it in two of the variables we created earlier. It then checks to see whether the movie clip's current position is at the new position. If it is not, it moves it closer to the new position based on the friction that we declared earlier. If it is at the new position, it then creates another new position for the object to move to.

4.

Test the movie.

Now when the test movie screen appears, you will see the circle_mc movie clip moving all over the stage from spot to spot, slowing down as it gets closer. Play with the friction variable to get some surprising results.

That example was not only powerful, but cool. You can try not only playing with the friction variable, but using other movie clip properties in conjunction with or without the _x and _y properties to see what else you can do. We will come back to this concept in later examples, but first we will cover another way you can manipulate movie clips. This time, we change their color.

Using the Color Object

The Color object is an object used to change the color or tint of a movie clip. It is unique among all other objects. Most objects, when created, have no association by default with other objects. The Color object, on the other hand, must be associated with a movie clip when the Color object is created.

Here is an example of creating a Color object:

 var myColor_color:Color = new Color(myMovie); 

The myMovie parameter is a reference to a movie clip that is either already on the stage or has been created with ActionScript.

The Color object has four basic methods, but we are going to focus on two of them, the setRGB() method and the setTransform() method. Both have unique attributes that make them suitable for different situations.

We will start with the setRGB() method because it is slightly easier to implement.

The setRGB() Method

The setRGB() method is used to set the RGB color of a movie clip. When called, it will change the color of the movie clip specified when the Color object was created to any legal hexadecimal color.

Here is the generic layout of the method:

 colorObj_color.setRGB(hexColor); 

The parameter it accepts, hexColor, can be any legal hexadecimal color such as 0x000000 (black), 0xffffff (white), or 0xff0000 (red). It can also be a variable that is holding a legal hexadecimal color.

NOTE

Hexadecimal colors are represented in the form of 0xRRGGBB, where RR is the red amount, GG is the green amount, and BB is the blue amount. Each of these sections range from 00 to FF where 0x000000 is black and 0xFFFFFF is white.


Here is an example of using the setRGB() method:

1.

Create a new Flash document.

2.

Draw a square somewhere on the stage with the fill color some shade of red.

3.

Highlight the square, including the stroke, and convert it to a movie clip symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of squareMC and make sure the behavior is set to Movie Clip.

5.

Give the instance of the square on the stage an instance name of square_mc.

6.

Create a new layer and call it actions.

7.

In the Actions layer, open the Actions panel in the first frame, and place these actions within it:

 //create the color object, and pass it the square_mc var myColor_color:Color = new Color(square_mc); //set the color to a light shade of blue myColor_color.setRGB(0x397dce); 

The preceding code creates a color object and associates itself with the movie clip we already created. Then it calls the setRGB() method and passes it a hexadecimal color that translates to a light shade of blue.

When you test the movie, you will see that the square_mc movie clip has changed from its original red color to a light shade of blue. Notice that it did not just change the fill color, but the stroke color has also now become the same shade of blue. The setTransform() method, discussed in the following section, does something a bit different.

The setTransform() Method

The setTransform() method is slightly different in the way it changes the color of a movie clip from the setRGB() method. Instead of changing the entire movie clip to a flat color, the setTransform() method tints the movie clip.

Here is the generic layout of the setTransform() method:

 myColor_color.setTransform(transformObject); 

This method has only one parameter when called, the transformObject. The TRansformObject is an object you create prior to calling the method that has special properties set. Following is a list of the available properties you can set for the transformObject:

  • ra The percentage for the red coloring ranging from 100 to 100

  • rb The offset for the red coloring ranging from 255 to 255

  • ga The percentage for the green coloring ranging from 100 to 100

  • gb The offset for the green coloring ranging from 255 to 255

  • ba The percentage for the blue coloring ranging from 100 to 100

  • bb The offset for the blue coloring ranging from 255 to 255

  • aa The percentage for alpha ranging from 100 to 100

  • ab The offset for alpha ranging from 255 to 255

That might be a little confusing until you see how to create one of these transformObjects. As with most things in Flash, there is more than one way to accomplish this.

Here is the long way:

 //first create the object var transformObject:Object = new Object(); //now set some of the properties of that object transformObject.rb = 200; transformObject.gb = 100; transformObject.bb = 50; transformObject.ab = 50; 

And here is the short way:

 //first create the object var transformObject:Object = {rb: '200', gb: '150', bb: '50', ab: '50'}; 

My personal preference is to use the long way, merely because it is easier to read and make corrections.

Now that you have seen the basic layout of not only the setTransform() method, but also the TRansformObject that we pass to the method, an example will bring it all together.

1.

Create a new Flash document.

2.

Draw a square somewhere on the stage with the fill color some shade of gray and the stroke color black.

3.

Highlight the square, including the stroke, and convert it to a movie clip symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of squareMC and make sure the behavior is set to Movie Clip.

5.

Give the instance of the square on the stage an instance name of square_mc.

6.

Create a new layer and call it actions.

7.

In the Actions layer, open the Actions panel in the first frame, and place these actions within it:

 //create the color object, and pass it the square_mc var myColor_color:Color = new Color(square_mc); //create the transformObject var transformObject:Object = new Object(); //now set some of the properties of that object transformObject.rb = 200; transformObject.gb = 100; transformObject.bb = 50; //finally call the setTransform() method myColor_color.setTransform(transformObject); 

The preceding code creates a Color object and associates it with our movie clip. Then it creates an object that we will use as the TRansformObject in our method. After that, it sets a few basic properties of the TRansformObject. And finally, the code calls the setTransform() method using the TRansformObject.

Now when you test the movie, the square_mc movie clip appears with a pinkish tint. Notice that this time, the stroke is not the exact color as the fill, but it is the same tint.

NOTE

If the setRGB() method is called, it will override the settings of the setTransform() method.


That was another way movie clips can be manipulated. So far we have covered how to move and adjust movie clips using the built-in properties. We have also discussed how to change their color using the Color object. The next section covers a new property of the movie clip object, blendMode.

The blendMode Property

The blendMode property is new to Flash 8, and it controls how colors interact when overlaid. We went over this option briefly in Chapter 1, showing how to set it manually in the Properties Inspector, but this time we will accomplish the same thing with ActionScript.

Setting the blendMode is no different from setting any other property of a movie clip. This property can be set to either a numerical value or a string literal. Here are the available options:

  • 1:normal This default option signifies that the pixel values of the blend image will override the pixel values of the base image.

  • 2:layer This option creates a temporary buffer for precomposition. This option is done automatically when there is more than one child in a movie clip and Normal is not selected.

  • 3:multiply This option multiplies the color values of the corresponding movie clips where they overlap, usually creating a darker color.

  • 4:screen The exact opposite of the multiply option, this option takes the complementing colors of the overlapping movie clips and creates a lighter color.

  • 5:lighten This option compares pixel colors of the overlapping images and displays the lighter of the two.

  • 6:darken This option compares pixel colors of the overlapping images and displays the darker of the two.

  • 7:difference This option compares pixel colors of the overlapping images and subtracts the darker color from the lighter color.

  • 8:add This option adds the overlapping pixel colors of the two movie clips and sets a maximum color of 0xff.

  • 9:subtract This option subtracts the overlapping pixel colors of the two movie clips and sets a minimum color of 0x00.

  • 10:invert This option inverts the background.

  • 11:alpha This option applies the alpha of the foreground onto the background, but only if the parent movie clip has a blend mode of layer set.

  • 12:erase This option "cuts out" part of the background with the foreground's alpha, but only if the parent movie clip has a blend mode of layer set.

  • 13:overlay This option multiplies the colors of the overlapping movie clips while preserving both highlights and shadows.

  • 14:hardlight This option, similar to the overlay option, multiplies or screens the two movie clips depending on their source color value. If it is darker than .5, it is multiplied. Otherwise, it is screened, or lightened.

Now let's see these blend modes in action by going through the next example.

1.

Create a new Flash document.

2.

Draw a red rectangle on the stage about 100x150 in size.

3.

Convert it to a movie clip called rec1MC with an instance name of rec1_mc.

4.

Draw a blue rectangle on the stage about 100x150 in size.

5.

Convert it to a movie clip called rec2MC with an instance name of rec2_mc and slide it over the red rectangle so that they overlap somewhat.

6.

Create a new layer called actions and place the following code in its first frame:

 //the blend mode variable var bM = 1; //each time the user clicks the mouse, go to the next mode this.onMouseDown = function(){    rec2_mc.blendMode = bM % 14 + 1;    trace(rec2_mc.blendMode);    bM++; } 

The preceding code first creates a variable that will hold the current blendMode. Then we use the onMouseDown event to iterate through each of the blend modes. And we use the trace function to show us which blend mode we are looking at.

Test the movie and each time you click, a new blend mode will be activated on the blue rectangle and the name of the blend mode will be displayed in the Output panel.

Another new way to manipulate the look and feel of a movie clip is using filters. We touched on them in Chapter 1, but we only went over how to control them manually. Now we will go over how to code them.

Filters

As mentioned in Chapter 1, filters are new to Flash 8, but if you have worked in applications such as Photoshop, they will not be new to you. Filters allow such things as drop shadow, blur, and a few other graphical effects to be applied to movie clips. Following is a full list of the available filters:

  • BevelFilter Creates a bevel effect on the movie clip.

  • BitmapFilter This is merely a base class for the other filters.

  • BlurFilter Creates a blur effect on the movie clip.

  • ColorMatrixFilter Allows the application of 4x5 transformation matrix with the RGBA for every pixel in the movie clip.

  • ConvolutionFilter Creates a matrix convolution effect.

  • DisplacementMapFilter This option allows you to displace specific pixels in the movie clip.

  • DropShadowFilter Creates a drop-shadow effect.

  • GlowFilter Creates a glow effect, both outer or inner.

  • GradientBevelFilter Creates gradient bevel effects.

  • GradientGlowFilter Creates a gradient glow effect, both outer and inner.

Follow these next steps to see how to create a dynamic drop-shadow effect on a movie clip:

1.

Create a new Flash document.

2.

Draw a rectangle in the middle of the stage about 200x200 in size.

3.

Convert the rectangle to a movie clip with the symbol name recMC and set the registration point to center-center.

4.

Back on the main stage, give the rectangle an instance name of rec_mc.

5.

Create a new layer called actions and place the following code in the first frame of that layer:

 //create an instance of the drop shadow effect var myShadow = new flash.filters.DropShadowFilter(); //set a few properties myShadow.blurX = 10; myShadow.blurY = 10; myShadow.distance = 10; //while the mouse moves, move the shadow around like the mouse is the light source this.onMouseMove = function() {   var yDist:Number = rec_mc._y - _ymouse;   var xDist:Number = rec_mc._x - _xmouse;   var degrees:Number = Math.atan2(yDist, xDist) / (Math.PI / 180);   myShadow.angle = degrees;   rec_mc.filters = [myShadow]; } 

When you test this movie, you will see as you move the mouse around the stage, the drop shadow will move as if the mouse cursor is the light source. You can see how this works in Figure 13.4.

Figure 13.4. Filters enable you to add perspective and better visual effects to your movie clips.


Of course, this was just one filter, but for more on filters, check the reference at the end of the book.

Now that you have adjusted a lot of visual aspects of movie clips, next you'll learn how to adjust their stacking order.

Depth and the Stacking Order

We briefly mentioned depth earlier in this chapter when we were creating movie clips with ActionScript. To recap, depth is a numerical value representing the stacking order of objects on the stage during runtime. And because each object, whether created manually or dynamically, has its own depth, no two objects can exist at the same depth.

The first method for working with depth management is the geTDepth() method.

The geTDepth() Method

The geTDepth() method will return a numerical value representing the depth of the object on which you call the method.

The generic layout is as follows:

 myMovie.getDepth(); 

This method has no parameters; it just needs to be associated with an object on the stage.

In the following example, you will create a movie clip manually and then use the getdepth() method to see what depth it is residing on.

1.

Start a new Flash document.

2.

Draw a circle on the stage.

3.

Convert the circle to a movie clip symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of circleMC and make sure the behavior is set to Movie Clip.

5.

Give the instance of the circle on the stage an instance name of circle_mc.

6.

Create a new layer and name it actions.

7.

In the first frame of the Actions layer, open the Actions panel and place this code in it:

 //send the depth of the movie clip to the output panel trace(circle_mc.getDepth()); 

The preceding code merely retrieves the depth of the circle_mc movie clip and sends it to the Output panel.

Test the movie and you should see the number 16383 in the Output panel. This is the first depth where objects created manually reside.

The geTDepth() method retrieves information about an object's depth, but if you want to change an object's depth using ActionScript, you have to use the swapDepths() method.

The swapDepths() Method

The swapDepths() method, as mentioned, is used to change the depth of movie clips whether created manually or with ActionScript. This method has two ways of working. Here are both of them in generic layouts:

 myMovie.swapDepths(depth); myMovie.swapDepths(target); 

Both uses have the myMovie in front of the method. This is the movie clip that you want to change the depth of.

Using the depth parameter, you will set a numerical value that will become the depth of myMovie. If there is already something on that depth, it will be moved to another available depth.

Using the target parameter, myMovie will change depths with the target movie clip. For the method to work correctly, both myMovie and target must reside within the same parent movie clip.

In this example, you will create two movie clips manually, align them slightly over one another, and then swap their depths so that at runtime, they will appear to have switched stacking orders.

1.

Start a new Flash document.

2.

Draw a circle on the stage.

3.

Convert the circle to a movie clip symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of circleMC and make sure the behavior is set to Movie Clip.

5.

Give the instance of the circle on the stage an instance name of circle_mc.

6.

While still in the same layer, draw a square shape (preferably with a different fill color, but that is not necessary).

7.

Convert the square to a movie clip symbol by choosing Modify, Convert to Symbol.

8.

Give it a symbol name of squareMC and make sure the behavior is set to Movie Clip.

9.

Give the instance of the square on the stage an instance name of square_mc and align it so that it is partially covering up the circle_mc movie clip, as in Figure 13.5.

Figure 13.5. Place the square over the circle on the stage.


10.

Create a new layer and name it actions.

11.

In the Actions layer, open the Actions panel in the first frame and place these actions in it:

 //swap the two movie clips depths square_mc.swapDepths(circle_mc); 

This code is simply swapping the two movie clips' depths with one another.

Test the movie, and you will see that now the circle movie clip appears above the square, as in Figure 13.6.

Figure 13.6. Now the circle appears above the square.


As you can see, it is important to know what depth movie clips are residing on, especially if you want to create them in ActionScript. Remember, two objects cannot reside on the same depth. Luckily, Flash has an easy way to find vacant depths, the getNextHighestDepth() method.

The getNextHighestDepth() Method

The getNextHighestDepth() method is used when creating movie clips in ActionScript. It returns the next available depth for a movie to be placed on as a numerical value starting with zero.

The generic layout is this:

 myMovie.getNextHighestDepth(); 

The myMovie in the code represents the movie clip that you are checking for the next available depth.

Here is a short example:

1.

Create a new Flash document.

2.

In the first frame of the main timeline, open the Actions panel and place these actions in it:

 //send the first available depth to the output panel trace(this.getNextHighestDepth()); //create a movie clip on the first available depth this.createEmptyMovieClip("test",this.getNextHighestDepth()); //send the next available depth to the output panel trace(this.getNextHighestDepth()); //output: 0 //        1 

The preceding code gets the first available depth and sends it to the Output panel. Then it creates a movie clip on the very same depth. Finally, it sends the next available depth to the Output panel.

Test the movie, and you should see an Output panel similar to Figure 13.7. Also, if you check the objects by clicking Debug, List Objects, you will see the movie clip we created in the Output panel as well.

Figure 13.7. Using the getNextHighestDepth() method, you will never have to worry if you are overwriting another movie clip's depth.


Sometimes you know a movie clip is on a certain depth, but you just cannot remember which movie clipmovie clip. Flash has a method for that as well, the getInstanceAtDepth() method.

The getInstanceAtDepth() Method

The getInstanceAtDepth() method is used to find out what object is residing on a certain depth. It returns the instance name of the object residing in the depth specified.

Here is a generic layout of the getInstanceAtDepth() method:

 myMovie.getInstanceAtDepth(depth); 

The only parameter the getInstanceAtDepth() method has is the depth parameter. This is the numerical value representing the depth you would like to check. If there is no instance on that depth, undefined will be returned.

Following is an example of using the getInstanceAtDepth() method:

1.

Create a new Flash document.

2.

In the first frame of the main timeline, open the Actions panel and place these actions in it:

 //create three movie clips on their own depth this.createEmptyMovieClip("sample1_mc",this.getNextHighestDepth()); this.createEmptyMovieClip("sample2_mc",this.getNextHighestDepth()); this.createEmptyMovieClip("sample3_mc",this.getNextHighestDepth()); //now check to see what is on depth 1 trace(this.getInstanceAtDepth(1)); 

The foregoing code creates three instances of movie clips and then returns the instance of the movie clip on depth 1.

Test the movie, and you will see in the Output window the instance name of the second movie clip we created. Remember the getNextHighestDepth() method starts at zero, not one.

We have covered many ways to manipulate movie clips, including their visual properties, color, and now their depth. The next section goes in a different direction by talking about how to make copies of movie clips during runtime.

Duplicating Movie Clips

Duplicating movie clips can be useful and more file-size efficient than manually creating each new movie clip. When you manually duplicate movie clips, the .swf file increases in size because not only does it include each new movie clip, but also all the code each extra movie clip contains. Using ActionScript to duplicate movie clips is more efficient because it duplicates the movie clips at runtime. The method used in ActionScript for duplicating movie clips is the duplicateMovieClip() method.

The duplicateMovieClip() Method

The duplicateMovieClip() method was introduced back in Flash 5; it has the capability to take movie clips created manually or with ActionScript and make duplicate copies on the stage during runtime.

Its generic layout is this:

 myMovie.duplicateMovieClip(instanceName, depth, initObject); 

myMovie is the movie clip to be duplicated. As you can see, the duplicateMovieClip() method has three parameters:

  • instanceName A string literal representing the instance name given to the duplicated movie clip being created

  • depth The depth of the duplicated movie clip as a numerical value

  • initObject An optional parameter referring to an object that the duplicated movie clip will retain all actions from

The duplicateMovieClip() is usually used in conjunction with a loop statement so that several copies can be made with one instance of the method.

Here is an example using the duplicateMovieClip() method:

1.

Create a new Flash document.

2.

Draw a square in the upper-left corner of the stage, about 50 pixels wide.

3.

Highlight the entire square, including the stroke, and convert it to a symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of squareMC and make the behavior Movie Clip.

5.

On the main stage, give the square an instance name of square_mc.

6.

Create a new layer and give it the name actions.

7.

In the first frame of the Actions layer, open the Actions panel and place these actions within it:

 //create a loop statement to control the duplication for(var i:Number = 0; i<10; i++){      //duplicate the movie clip      square_mc.duplicateMovieClip("square"+i+"_mc",i); } 

The preceding code uses a for loop statement to control the duplication of the movie clip. Then, in the duplicateMovieClip() method, we use the variable i that was created in the loop statement to give each instance of the duplicated movie clip a unique instance name and depth; two movie clips cannot have the same instance name or reside on the same depth.

Test the movie and notice that it appears that the duplication did not take place. But in fact it did work; select Debug, List Objects, and the Output panel will show all the duplicated movie clips, as you can see in Figure 13.8.

Figure 13.8. The Output panel shows that the duplicateMovieClip() method was successful, even if the results on the stage appear otherwise.


Let's go back into the code to create a visual indicator that the duplicateMovieClip() method is working.

1.

Close the test movie screen and go back to the main timeline.

2.

Open the Actions panel in the first frame of the actions layer and change the code to this:

 //create a loop statement to control the duplication for(var i:Number = 0; i<10; i++){      //duplicate the movie clip      var ref:MovieClip = square_mc.duplicateMovieClip("square"+i+"_mc",i);      //the following code will show visual appearance of the other movies      ref._x += square_mc._width*i; } 

The preceding code is very similar to the code that was there before. The first difference you will notice is that we create a reference named ref so that we can access the duplicated movie clip's properties after it has been created. Then we move the square to the right by an amount equal to its own width, which will create a line of squares.

Test the movie again, and you should see that the duplicateMovieClip() method did in fact work, with each square being spaced out across the stage as shown in Figure 13.9.

Figure 13.9. You can see that the duplicateMovieClip() method worked, because the squares are spaced along the stage.


The next example is going to take into consideration all that we have covered thus far. We will use the code that will make movie clips move around on the screen and we'll make use of the Color object and the duplicateMovieClip() object.

1.

Create a new Flash document.

2.

Draw a circle on the stage.

3.

Convert the circle to a Movie Clip symbol by choosing Modify, Convert to Symbol.

4.

Give it a symbol name of circleMC and make sure the behavior is set to Movie Clip.

5.

Give the circle on the stage an instance name of circle_mc.

6.

Create a new layer and name it actions.

7.

In the first frame of the Actions layer, open the Actions panel and place this code in it:

 //set the cacheAsBitmap property circle_mc.cacheAsBitmap = true; //place some variables associated with circle_mc circle_mc.friction = 0.3; circle_mc.xBoundary = 550; circle_mc.yBoundary = 400; circle_mc.newX = Math.floor(Math.random()*circle_mc.xBoundary); circle_mc.newY = Math.floor(Math.random()*circle_mc.yBoundary); 

The preceding code creates variables associated with the circle_mc movie clip.

8.

Next we will create a Color object, and use the Math object to select a random color. Place this code after the preceding code:

 //this will color the circle_mc circle_mc.newColor = new Color(this); //set the RGB using the Math.random() method circle_mc.newColor.setRGB(Math.random()*0x1000000); 

This section of code creates a Color object within the circle_mc movie clip. You will see later why we are putting the variables and Color object in the circle_mc. After the Color object is created, we call the setRGB() method and pass it a random hexadecimal value by using the Math.random() method.

You can test the movie at this point if you like. Every time the movie is run, the color of the circle will change to a random color.

The next block of code will be used to move the circle around.

9.

After the preceding block of code in the Actions panel, add these actions:

 //this is the event for the motion circle_mc.onEnterFrame=function(){      //continually get the current position      currentX = Math.floor(this._x);      currentY = Math.floor(this._y);      //check the horizontal position      if(currentX != this.newX){           this._x += (this.newX-currentX)*this.friction;      }else{           this.newX = Math.floor(Math.random()*this.xBoundary);      }      //do the same with the horizontal position      if(currentY != this.newY){           this._y += (this.newY-currentY)*this.friction;      }else{           this.newY = Math.floor(Math.random()*this.yBoundary);      } } 

This code creates the function that will control the movement of the circles. You can test again here if you like to see that the circle_mc is moving around. Now all we have to do is make copies.

10.

Now we'll create the final part of the code, the duplicating part. Add these actions to the bottom of the code we already have:

 //this will duplicate the movie for(var i=0; i<10; i++){      circle_mc.duplicateMovieClip("circle"+i+"_mc",i, circle_mc); } 

This code duplicates the movie clip we have already built and uses the circle_mc as its initializing object, which means that each duplicate movie clip will take on the same characteristics as the object we place in there.

Now test the movie again, and you should see a bunch of circles flying around the screen, as shown in Figure 13.10. And each time you run this movie, their color will change.

Figure 13.10. Using the duplicateMovieClip() method, you can create some cool effects.


We have seen how to create movie clips two different ways, as well as duplicate them. But what if we want to remove them?




Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net