Drag and drop multiple shapes

In the movie below you can drag and drop any of the shapes.
Get Adobe Flash player

In this movie, we want to be able to drag and drop several objects. The instance names are ball, box, and star. We could repeat all of the code for all of the objects. Instead we will call the same function for each object and use the target of the event or the object that the event occurred for instead of a specific name. The code is shown below:

ball.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
ball.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
box.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
box.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
star.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
star.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);

function clickToDrag(e:MouseEvent):void {
	e.target.startDrag(); //the target is whichever shape received the event
}

function releaseToDrop(e:MouseEvent):void {
	e.target.stopDrag(); //the target is whichever shape received the event
}

Download the movie
INDEX, A simple drag and drop example, e.target: Using the same code for many shapes, Dynamically generated stars, Drag and drop dynamically generated shapes, Naming dynamically generated stars
Next lesson: Hit Test

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

e.target: Using the same code for many shapes