Search code examples
actionscript-3

Timed plays of different instances of the same object


I want to make a bunch on instances of the same object (small ball in my case), that has its own timeline and its own animation, but I want the animations to come sequentially, one after the other.

Here's the code:

var balls:Array = new Array();
var i:int;
i = 0;
while (i<5)
{
    balls[i] = new animBall();
    balls[i].x = balls[i].x + i * 100;
    drawBall(balls[i]);
    balls[i].gotoAndPlay(2);
//here i really need something like a "wait 500 ms" function
    i++;
}

Everything runs at the same time. Another idea is to use timers, but it feels like overkill, maybe there's a better way to do this?

I would love to refrain from putting code all over the .fla, so I would rather have all code in one place, instead of a little bit here, little bit there.


Solution

  • You could solve this problem through recursion, where a function calls itself again and again until a condition has been met.

    var balls:Array = new Array();
    var i:int = 0;
    var end:int = 5;
    var delay:int = 1000; //1000ms = 1s
    
    recursiveLoop();
    
    function recursiveLoop():void{
      balls[i] = new animBall();
      balls[i].x = balls[i].x + i *100;
      drawBalls(balls[i]);
      balls[i].goToAndPlay(2);
      i++;
      if(i != end){
        setTimeout(recursiveLoop,delay); //wait 1 second then call the function again
      }else{
        //you will end up here once every balls has been created
      }
    }
    

    Like you said yourself, this could also be solved through the Timer Class. And it wouldn't be much more code, without writing it out I think you could solve it through timer with 2 functions.

    Edit.: And before I forget, here is something very important that you should look out for. look at the following function call:

       setTimeout(recursiveLoop,delay);
    

    the function recursiveLoop has no () besides its name. Why though? Well, if you try it with the () on the function, the function will get called immediately instead of waiting until the delay has run out. So remember to be very careful when you reference functions as parameters for other functions. You might also ask yourself how to pass parameters to the recursiveLoop() function. Well, with setTimeout it will be awkward. But Greensocks Tweening Library has also something to call a function after a period of time, but also with parameters if you wish.