Loops

In this movie we have a star that is a Spinner. We want to be able to add the stars when we click on the starField, but also be able to stop all of the stars, or speed them up.

The stars have to be put in a container because if we just add them to the stage, then when we click one of the buttons it puts a star on top of the button and you can't click the button anymore.

Get Adobe Flash player
The code is shown below:

import flash.events.MouseEvent;
btnStop.addEventListener(MouseEvent.CLICK,stopAll);
btnFast.addEventListener(MouseEvent.CLICK,speedAll);
btnSlow.addEventListener(MouseEvent.CLICK,slowAll);
btnClear.addEventListener(MouseEvent.CLICK,deleteAll);
starField.addEventListener(MouseEvent.CLICK, addStar);
function addStar(e:MouseEvent):void {
   var s:Star = new Star(); //create a new star
   s.x=e.localX; //set the x property to the point in the starField clicked
   s.y=e.localY; //set the y property to the point in the starField clicked
   s.width=Math.random()*50+20;
   s.height=s.width;
   do {
     s.speed=(Math.random()*10)-5;
   } while(s.speed==0); //this makes sure that the speed is not 0
   starField.addChild(s); //add the new star to the movie
}
function deleteAll(e:MouseEvent):void {
   var d:DisplayObject;
   var i:int=0;
   while(i<starField.numChildren) {
      d=starField.getChildAt(i);
      if(d is Spinner) {  //we don't want to remove the buttons or the colored background
         starField.removeChildAt(i);
         //after deleting this one the next child will be in position i
      }
      else i++; //if the child was not deleted go to the next one
  } //all of the children
}//deleteAll

function stopAll(e:MouseEvent):void {
  var d:DisplayObject;
  var i:int;
  for(i=0;i<starField.numChildren;i++) {
    d=starField.getChildAt(i);
    if(d is Spinner) {
      d["speed"]=0;
    } //child is a spinner
  } //all of the children
}//stopAll
function speedAll(e:MouseEvent):void {
  var d:DisplayObject;
  var s:Star;
  var i:int;
  for(i=0;i<starField.numChildren;i++) {
    d=starField.getChildAt(i);
    if(d is Spinner) {
      if(d["speed"]<0) d["speed"]-=1; 
      else d["speed"]+=1;
    } //child is a spinner
  } //all of the children
}//speedAll
function slowAll(e:MouseEvent):void {
  var d:DisplayObject;
  var s:Star;
  var i:int;
  for(i=0;i<starField.numChildren;i++) {
    d=starField.getChildAt(i);
    if(d is Spinner) {
    if(d["speed"]<0) d["speed"]+=1; 
    else if(d["speed"]>0) d["speed"]-=1;
     //don't change speed if it is 0
  } //child is a spinner
  } //all of the children
}//slowAll
Download the movie

Experiment:

  • Add a button that will reset all of the stars to a random speed.
  • Add a button that will make all of the stars spin in the opposite direction.

NEXT: Arrays