Loops

Before we do the example below, you should know that the statement star.x=5; can also be written as this["star"].x=5;

If we have a movie clip called star1 we can rotate it using any of the statements below:

this.addEventListener(Event.ENTER_FRAME,frames);
function frames(e:Event):void {
  var num:int=0;
  while(num<4) { 
    this["star"+num].rotation++;
    num++;
  } //loop
}//frames

The last format comes in really handy when we have several stars to rotate and we want to use a loop.

Spinning Stars

Get Adobe Flash player

Displaying numbers in the output window is not very exciting, let's do something practical, like making a bunch of stars spin.

• On the stage draw a star and make it a movie clip called Star with the registration point in the center.
• Put 4 instances of the Star on the stage.
• Name the instances star0, star1, star2, and star3.
• Write the following code:
this.addEventListener(Event.ENTER_FRAME,frames);
function frames(e:Event):void {
  var num:int=0;
  while(num<4) { 
    this["star"+num].rotation++;
    num++;
  } //loop
}//frames

When you test the movie you will see all of the stars spinning. If there is no instance named star0, star1, star2, or star3 you will get an error message.
Notice the indentation: all statement within { and } are indented the same amount for readability.

Experiment:

  • Make the stars spin faster.
  • Make all of the stars move in addition to spinning.
  • Declare a variable numStars and use that in the loop instead of 4.
  • Use a for or do while instead of a while loop.

NEXT: Stop stars created dynamically