ActionScript3:Drag and Drop with Targets

From virtualMV2015wiki
Jump to: navigation, search
 Home  Flash11 (CS5) | Flash10 (CS4) <

Introduction

Drag and Drop introduces some user interactivity with your Flash Movie.

Icon Objective.png

Objective

By the end of this exercises you should be able to:

  • Create a small movie with draggable objects and drop targets using Actionscript 3.

Instructions

Setting the Stage

Create a new Actionscript3 movie. Rename the first layer to Background. Import a graphic to the stage, or draw one. In this case a frog. Lock the layer. Create a new layer and name it CrownTarget. Create a new layer and name it CrownMc.(The assets used in this tutorial are available here: Crown and Frog). Create a new layer and call it Text. With Actionscript 3, it is important to get the layering right. In this case we need to have the target layer below the crown layer. Create a new layer and name it actions. Your timeline should be layered as in the diagram below:

Sd timelineAS3.png

Import the assets to the library, if you havent already done so. Convert the crown graphic to a Movieclip and give it a meaningful name. With Frame One of the CrownMc layer selected, drag the Crown Movieclip from the library and onto the side of the stage. Then give the instance of the movieclip a name, in this case I've kept it simple and called it crownMc. Lock the layer.

Sd NamingInstance.png

Select frame One of the CrownTarget layer, and drag from the library the same MovieClip. Give it an instance name of targetcrownMc. Place it in position, on top of the frogs head. Reduce the alpha to "0" so the target becomes invisible. Lock the layer.

Adding the Actionscript

Select frame one of the Actions layer, open the actions panel and enter the following code to allow us to drag and drop the crown.


crownMc.addEventListener(MouseEvent.MOUSE_DOWN, pickMe);
crownMc.addEventListener(MouseEvent.MOUSE_UP, dropMe);
function pickMe(event:MouseEvent):void {
    event.target.startDrag(true);
}
function dropMe(event:MouseEvent):void {
    event.target.stopDrag();
}
crownMc.buttonMode = true;

This code initiates dragging the movie clip when the mouse button is pressed and to stop when the mouse button is released. In ActionScript3, this is created by setting an event listener for each event, MOUSE_DOWN and MOUSE_UP and assigning event handler functions (in this case called pickMe and dropMe) to tell Flash what to do once the event is triggered, event.target refers to the object that initiated this event, which in this case will be crownMc. Using event.target instead of naming the object specifically will allow the code to be reused, no matter how many draggable piece there are on the stage. In this small tutorial, there is only one, but you may add many. Refer to the extensions below to see the additional code needed to reuse these functions for different draggable objects. The “true” parameter of the startDrag function causes the shape to be picked up from its center, which eases placement. To display the hand cursor when clicking movieclip symbols, the buttonMode property is set to true.

Test the movie. You should be able to pick up the crown and move it around the stage and drop it anywhere. Problems at this stage occur if the names used in the ActionScript DO NOT match exactly those given for the instance naming of the crown. Check if necessary.

Locking the Crown into place

Once the crown is able to be dragged around, the next stage is to get it to lock onto the target IF its dropped in the correct place. This is done by removing the event listeners once the target is met and removing the hand symbol by setting the buttonMode to false. Locking into the exact position requires matching the x and y coordinates. Add the following code within the dropMe event handler, after the line event.target.stopDrag().

Sd hottipicon.png HOT TIP! It is important to note the naming of the target Movieclip at this stage also, as the myTargetName variable depends on correct naming.


var myTargetName:String = "target" + event.target.name;
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
        event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickMe);
        event.target.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
        event.target.buttonMode = false;
        event.target.x = myTarget.x;
        event.target.y = myTarget.y;
}

Repositioning Incorrectly Placed Objects

If the crown is dropped in the wrong place, it can snap back to its original position by storing the start X and Y coordinates in a variable and using this information in the pickMe function.

Add the following ActionScript to set up the variables, above all the other ActionScript on Frame One:

var startX:Number;
var startY:Number;

Then, add the following code to the pickMe function, just below the code event.target.startDrag(true); :

startX = event.target.x;
startY = event.target.y;

and the following code within an else statement at the end of the dropMe function:

event.target.x = startX;
event.target.y = startY;

Test the movie. The crown should return to its original position if not dropped on the frogs head in the correct place.

The Complete Code

var startX:Number;
var startY:Number;
 
crownMc.addEventListener(MouseEvent.MOUSE_DOWN, pickMe);
crownMc.addEventListener(MouseEvent.MOUSE_UP, dropMe);
 
function pickMe(event:MouseEvent):void {
    event.target.startDrag(true);
    startX = event.target.x;
    startY = event.target.y;
}
function dropMe(event:MouseEvent):void {
    event.target.stopDrag();
    var myTargetName:String = "target" + event.target.name;
    var myTarget:DisplayObject = getChildByName(myTargetName);
    if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
        event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickMe);
        event.target.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
        event.target.buttonMode = false;
        event.target.x = myTarget.x;
        event.target.y = myTarget.y;
 
    } else {
        event.target.x = startX;
        event.target.y = startY;
    }
 
}
 
 crownMc.buttonMode = true;

Extensions

Reusing the functions with more than one drag and drop target

Quite often, there will be a need to have more than one draggable object on the stage as well as more than one target object. With ActionScript 3, there is no need to repeat the code, just adding in a few extra line and reusing the functions is all that is required.

For a second object to drag, just add the following code below the corresponding code for crownMc,:

secondObjectMc.addEventListener(MouseEvent.MOUSE_DOWN, pickMe);
secondObjectMc.addEventListener(MouseEvent.MOUSE_UP, dropMe);

and to finish, add underneath the corresponding crownMc code:

secondObjectMc.buttonMode = true;


as long as the target name is targetsecondObjectMc, this additional code is all that is needed for the drag and drop to work on the second object. You can repeat this as many times over as many objects as you need to drag and drop on the stage.

Keeping track of the Drop Count

Like in the ActionScript 2 exercise, keeping track of the number of correct drops can be useful if you need something to happen when the drops are complete - display a message, move along the timeline etc.

Add a dropCount variable to the beginning of the ActionScript on the actions layer, frame One.

var dropCount:Number = 0;

then, within the dropMe event handler, increment the dropCount variable. Add this ActionScript to the end of the IF statement:

dropCount++;

Within the same event handler, and after the last ELSE statement add the following ActionScript to populate a text box with a message. You will need to make sure there is an empty text box in frame One of the text layer - in this case with the name handsome_txt:

if(dropCount == 1){
handsome_txt.text = "No Handsome Prince under this Crown!";
}

The Completed Drag and Drop

Try Me

ActionScript 3 and the Z index

ActionScript 3 allows you to control the depth of an object. In Actionscript 2, if an object was below another in the layering order, it stayed there. ActionScript 3 allows you to bring that object to the top. In the above example, if there were more than one object to drag, you could ensure the one you clicked on dragged over the others regardless, by adding the following code to the pickMe event handler, directly below the code event.target.startDrag(true); :

event.target.parent.addChild(event.target);

Resources

Flash Drag and Drop Tutorial at Edutech Wiki [1]


Icon References.png References

  1. Daniel K. Schneider (May 2010). Flash Drag and Drop Tutorial, Retrieved August 18, 2010, from http://edutechwiki.unige.ch/en/Flash_drag_and_drop_tutorial

 

Day, S. (2010). ActionScript3:Drag and Drop with Targets. Retrieved December 14, 2017, from http://www.virtualmv.com/wiki/index.php?title=ActionScript3%3ADrag_and_Drop_with_Targets