Notes to Lesson 8d

$movingSquare->moveTo(40,40);
for($i=0; $i<12; $i++){

In the above loop statement, the $i++ is the same as adding the number 1 from 0-12 during the loop. You could also have written $i+=1; which will add a value of 1 from the beginning to the end of the loop. You can change that number to 2 and it will loop through the numbers counting only the even numbers, 2, 4, 6, etc. This generally will make a loop move faster, because instead of moving only 1 pixel at a time, it will be moving 2 pixels at a time, at the same rate. This kind of loop manipulation is especially useful for more complex loops where variables inside the loops are made to move in a specific way. In a simpler example, such as the one used in these examples, you can manipulate the image somewhat by changing the beginning and end number. It will not run across the page, but may start and end before the left or right side of the page. The behavior of loops becomes more apparent the more you use them. If you changed the loop, as below, in lesson 8b, the square would move in the opposite direction across the page.

$movingSquare->moveTo(440,40);
for($i=12; $i>0; $i--){
$myMovie->nextFrame();
$movingSquare->rotate(15);
$movingSquare->move(-20,0);
if($i < 0 OR $i > 23){
break;
}
}
First the square is placed on the other side of the page (440,40), then the for statement counts backwards from 12 to 0, the square is rotated 15 and moved -20. I have also placed an if statement inside the loop to handle any errors that might occur in the loop. I may have misstyped the $i-- and used $i++ instead. That would tell the loop to keeping adding 1 to the starting number of 23, so long as it is over 0. This is an infinite loop and will go on forever, eat up memory, and you will never see any movement on your swf. The if statement tells the loop that if it counts a number outside of its parameters, to break out of the loop and stop counting.

Result:



There are other loops that prove to be useful in Ming movies. I will put them here for you to come back to when you are more familiar with loops.

This loop is called a while loop.
LOOP TWO VARIABLES AT SAME TIME.
$x=0;
$x2=608;
while($x>-690){
$myMovie->nextFrame();
$x=$x-2;
$x2=$x2-2;
$Variable1->moveTo($x,0);
$Variable2->moveTo($x2,0);
}

SCALE AND MOVE AN IMAGE
$x=0;
$y=0;
$z=1.0;
while($x>-125){
$x=$x-2;
$z=$z+0.05;
$y=$x;
$myMovie->nextFrame();
$Variable1->scaleTo($z);
$Variable1->moveTo($x,$y);
}

This is a while loop inside a loop, which will do something until $x reaches the number in the if statement. Then it will perform what is inside the if statement, at the same time. Once that second task is completed, it will continue the first loop until the end.

$x=400;
$x2=60;
while($x>0){
$myMovie->nextFrame();
$x=$x-2;
$Variable1->moveTo($x,0);
if($x == 100){
$x2=$x2-2;
$Variable2->moveTo($x2,0);
Continue;
}
}