Start and Stop dynamically generated Spinner stars

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;
btnStop.addEventListener(MouseEvent.CLICK,goButtons);
btnGo.addEventListener(MouseEvent.CLICK, goButtons);
for(var i:int=0;i<numStars;i++) {
    var str:Star = new Star();
    str.x=Math.random()*stage.stageWidth;
    str.y=Math.random()*stage.stageHeight;  
    str.name="star"+i;  //see below
    this.addChild(str);
    str.addEventListener(MouseEvent.MOUSE_DOWN, clickDrag);
    str.addEventListener(MouseEvent.MOUSE_UP,releaseDrop);
}
function goButtons(e:MouseEvent):void {
    //trace(e.target.name);
    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{
   e.target.startDrag();
}
function releaseDrop(e:MouseEvent):void{
   e.target.stopDrag();
}

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.

 
 

Naming dynamically generated stars