Drag and Drop

In the movie below Star has been made a Spinner. You can drag and drop any of the stars, plus start and stop them. Get Adobe Flash player

In this movie we generate 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. Notice that the two buttons call that same function and we use e.target to tell which button was clicked.

Speed is a public variable in the Spinner Class.

The name given to dynamicaly generated objects is not the same as the instance name that is given to objects on the stage. We can access the name, as shown below, using getChildByName.

The code is shown below:

var numStars:int=10;
btnGo.addEventListener(MouseEvent.CLICK, goButtons);
for(var i:int=0;i<numStars;i++) {
    var str:Star = new Star();
    str.name="star"+i;  //see below
    str.addEventListener(MouseEvent.MOUSE_DOWN, clickDrag);
function goButtons(e:MouseEvent):void {
    for(var i:int=0;i<numStars;i++) {
       var str= this.getChildByName("star"+i);
       if(e.target.name=="btnStop") str.speed=0;
       if(e.target.name=="btnGo") str.speed+=1;
       if(e.target.name=="btnFaster") str.speed+=1;
    } //for i
} //goStop
function clickDrag(e:MouseEvent):void{
function releaseDrop(e:MouseEvent):void{

Download the movie

NEXT: Hit Test