Drag and Drop

In the movie below you can drag and drop any of the stars.

Get Adobe Flash player

In this movie we generate 10 stars using a loop. Inside the loop we add event listeners so that we will be able to drag and drop any of the stars. We use the same code to drag and drop the target that we used previously. The code is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for(var i:int=0;i<10;i++) { //generate 10 stars
   var str:Star=new Star();
   str.x=Math.random()*stage.stageWidth;
   str.y=Math.random()*stage.stageHeight;
   this.addChild(str);
   str.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag); //each one can be dragged
   str.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop); //... and dropped
}
function clickToDrag(e:MouseEvent):void {
   e.target.startDrag(); //the target is whichever star received the event
}

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

Download the movie

NEXT: Naming dynamically generated stars