Creating Draggable Movie Clips


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

Drag-And-Drop Basics

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

  1. Start a new Flash document. Rename Layer 1 to mcDrag.

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

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

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

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

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

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

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

    Tip 

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

  6. Save your Flash document as movieclip_button_drag.fla. Test your movie with Control Test Movie (Ctrl+Enter or z+Enter). Click the circle and drag it around the Stage. To stop dragging, release the mouse button.

    On the CD-ROM 

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

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

Lock Mouse to Center

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

 mcDrag.startDrag(true); 

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

 mcDrag.startDrag(false); 

Constrain to Rectangle

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

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

Note 

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

Detecting the Drop Position: Using _droptarget

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

  1. Open a new Flash document (File New), and save it as movieclip_droptarget.fla .

  2. Rename Layer 1 to mcCircle.

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

  4. Copy the mcCircle instance by selecting it on the Stage and choosing Edit Copy (Ctrl+C or z+C).

  5. Create a new layer, and name the layer mcCircleBig. Place the layer below the mcCircle layer.

  6. On frame 1 of the mcCircleBig layer, choose Edit Paste (Ctrl+V or z+V). Place the new copy above the original instance, as shown in Figure 25-5. Scale the artwork to 125 percent in the Transform panel, and name the instance mcCircleBig in the Property inspector.

  7. Create a new Movie Clip symbol from scratch by choosing Insert New Symbol (Ctrl+F8 or z+F8). Name the symbol statusClip. Inside of this symbol, create a short animation displaying the text "Correct!" Leave the first frame of the symbol empty, and create the text (and supporting tweens, if desired) on frame 2 and higher. Create a frame label named correct on frame 2 of a new layer named labels, as shown in Figure 25-6. Also, place a stop(); action on frame 1 of an actions layer in the timeline.

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

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

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

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

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

     mcCircle.onRelease = mcCircle.onReleaseOutside = function(){   this.stopDrag();   if (eval(this._droptarget) == mcCircleBig) {     mcStatus.gotoAndPlay ("correct");   } else {     this._x = 112;     this._y = 316;   } }; 

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

    Note 

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

  11. Save your Flash document as movieclip_droptarget.fla, and test it (Ctrl+Enter or z+Enter). Click and drag the mcCircle instance on top of the mcCircleBig instance. The dragged instance will stay put on top of the larger circle, and the "Correct!" message will animate. Click and drag the mcCircle instance off the mcCircleBig instance, and release the drag outside of the larger circle. The smaller circle will snap back to its original starting point.

image from book
Figure 25-4: The mcCircle instance

image from book
Figure 25-5: The mcCircleBig instance

image from book
Figure 25-6: The statusClip symbol timeline with a Blur filter tween

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

On the CD-ROM 

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

Making Alpha, Scale, and Blur Sliders

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

On the CD-ROM 

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

Assembling the Parts

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

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

  2. Rename Layer 1 to mcDog_1.

  3. Access the document's Library by pressing Ctrl+L or z+L. Open the dogElements folder, and drag the dogClip symbol onto the Stage. Place the instance in the upper-left corner of the Stage.

  4. With the dogClip instance selected, open the Property inspector. In the <Instance Name> field, type mcDog_1, as shown in Figure 25-7.

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

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

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

     var mcDog_1:MovieClip; mcDog_1.duplicateMovieClip("mcDog_2", 1, {_x: 350,_y: 175}); 

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

  8. Save the Flash document, and test the movie (Ctrl+Enter or z+Enter). You should see a new instance of the mcDog_1 Movie Clip appear on the right side of the Stage (see Figure 25-9).

image from book
Figure 25-7: The mcDog_1 instance will be used as your reference MovieClip object. The scale and transparency of this dog instance will not be changed.

image from book
Figure 25-8: The mcSign instance will be used to remove duplicates of the mcDog_1 Movie Clip instance.

image from book
Figure 25-9: The duplicateMovieClip() method creates a new instance of a MovieClip object. Unless you alter the new instance's X and Y positions, it will appear directly above the parent instance.

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

Building the Sliders

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

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

On the CD-ROM 

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

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

  2. Create a new Movie Clip symbol (Ctrl+F8 or z+F8) and name it sliderClip. In Edit mode, rename the first layer sliderRule. On this layer, drag an instance of the sliderRuleGraphic symbol (located in the sliderBarElements folder of the Library) onto the Movie Clip Stage.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

image from book
Figure 25-11: The starting X coordinate for the mcPos Movie Clip instance is set to 100. When the Flash movie starts, this value will be applied to the scale and alpha properties of the mcDog_2 instance on the Main Timeline.

image from book
Figure 25-12: At this point, your Flash document's Stage should contain the dogClip and parkSignClip artwork, as well as two instances of the sliderClip symbol.

Checking the Positions of the Sliders

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

On the CD-ROM 

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

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

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

     this.onEnterFrame = function():Void {    var nScale:Number = mcScale.mcPos._x;    var nAlpha:Number = mcAlpha.mcPos._x;    with (mcDog_2) {      _xscale = nScale;      _yscale = nScale;      _alpha = nAlpha;    } }; 

    Because the event method onEnterFrame() is specified for the Main Timeline (this), this block of code will execute continuously in your Flash movie. Why? Any timeline will continuously enter a frame for playback, even if a stop() action is applied to all timelines. The speed at which the enterFrame event occurs is determined by the frame rate of the Flash movie (as defined by the Modify Document dialog box). The frame rate of 12 fps was already set in the sample file before you opened it. Therefore, this block will execute 12 times each second.

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

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

    Note 

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

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

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

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

     _alpha = nAlpha/2; 

  5. Save your Flash document and test it. Now, as you drag up with the bar for the mcAlpha instance, the opacity increases. As you drag down, it decreases.

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

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

     mcAlpha.mcPos._x = 200; 

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

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

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

  9. Name the new copied instance mcBlur in the Property inspector, and position the instance near the top of the mcAlpha slider, parallel to the mcScale slider.

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

     this.onEnterFrame = function():Void {    var nScale:Number = mcScale.mcPos._x;    var nAlpha:Number = mcAlpha.mcPos._x;    var nBlur:Number = mcBlur.mcPos._x;    var bf:flash.filters.BlurFilter = new       flash.filters.BlurFilter();    bf.blurX = nBlur/2;    bf.blurY = nBlur/2;    bf.quality = 3;    with (mcDog_2) {       _xscale = nScale;       _yscale = nScale;       _alpha = nAlpha/2;       filters = [bf];    } }; 

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

  11. Save the Flash document, and test the movie. The mcDog_2 instance should now initialize with a blurred look, as shown in Figure 25-13.

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

     mcBlur.mcPos._x = 0; 

  13. Save the Flash document, and test it. Now, the mcBlur slider starts at a blurX and blurY value of 0.

image from book
Figure 25-13: The new BlurFilter effect applied to the mcDog_2 instance.

Removing Movie Clips

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

On the CD-ROM 

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

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

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

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

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

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

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

    Note 

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

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

On the CD-ROM 

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

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

Web Resource 

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




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

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