Drag and Drop

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
}
CODE

Download the movie

NEXT: Dynamically generated stars