Thursday, 4 June 2009

Drag and drop in AS3 part 2

This is a continuation of the Drag and drop in AS3 tutorial. In this brief tutorial I will be modifying the existing code, so that it can be used multiple times. This is useful if you are required to drag and drop several objects without writing multiple lines of code. In this tutorial I will be using three objects to demonstrate the drag and drop functionality.

Drag and drop in AS3 part 2

Step 1

Open a new flash document.
Create your objects on the stage. I have created three primitive shapes using the basic shape tools. You can create whatever objects you wish.




Step 2

Convert your objects into symbols by pressing F8.
Give your symbols appropriate names, check movie clip and click ok.
Select your object using the selection tool (V) and give the instance name: red_mc, green, and blue_mc.


Step 3

On the timeline insert a new layer called “actions” right click on the first frame and select Actions from the drop down menu.

Add the following code:

red_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
red_mc.addEventListener(MouseEvent.MOUSE_UP, drop);
green_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
green_mc.addEventListener(MouseEvent.MOUSE_UP, drop);
blue_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
blue_mc.addEventListener(MouseEvent.MOUSE_UP, drop);

function drag(event:MouseEvent):void {
event.target.startDrag();
}

function drop(event:MouseEvent):void {
event.target.stopDrag();
}

**The first six lines of code add events listeners for each of the objects created on the stage. The event listeners are for the mouse up and mouse down events with include the drop and drop event handlers.

This time the “event.target” was used in the drag and drop functions. The event.target refers to the objects that start the event. This would be the objects: red_mc, green_mc, and blue_mc. Using the event.target avoids creating three separate drag and drop functions which need to be specified separately.


Step 4

Test your movie Ctrl + Enter. Now use your mouse to drag and drop the various objects.



You should now be able to drag and drop multiple objects using the same code.

1 comments:

Anonymous 26 June 2009 at 11:54  

Cool, this has really helped me with actionscript. :)

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP