jdfinch3
jdfinch3

Reputation: 513

AS3 - How do you wait for a tween inside a for loop to complete?

I'm drawing a large shape using an array of points in a for loop and tweenlite as found at http://www.flashperfection.com/tutorials/Animated-line-drawing-using-TweenLite-in-AS3-22013.html

for(var i:uint = 0; i < pointsArray.length; i++){
TweenLite.to(dot2, .05, {x:pointsArray[i].x,
  y:pointsArray[i].y,
  delay:i*.05,
  overwrite:false,
 onUpdate:updateHandler});
}
function updateHandler():void{
lineAnim.graphics.lineTo(dot2.x, dot2.y);
lineAnim.graphics.moveTo(dot2.x, dot2.y);
}

I would like the animation to complete before continuing, but I'm unable to find a way to be notified when the full animation is complete. onComplete does not work as it triggers on the first set of coords. I also tried triggering when

i == pointsArray.length

but the loop finishes multiple seconds before the animation completes. I would like to avoid using a timer.

Upvotes: 0

Views: 569

Answers (2)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

You could do an asynchronous loop by doing something like the following:

var curIndex:int = 0; //a var to hold the current index of the points array
tweenItem();

//a function to call every time a tween is finished
function tweenItem(){
    if(curIndex >= pointsArray.length){
        //all done, do something
        return;
    }

    TweenLite.to(dot2, .05, {
        x:pointsArray[curIndex].x,
        y:pointsArray[curIndex].y,
        onUpdate:updateHandler,
        onComplete: tweenItem //call this function again once the tween completes
    });

    curIndex++; //incriment the index
}

Now, you could save yourself the trouble and just use TimelineLite, made by the same author, which makes sequencing multiple tweens very easy.

Upvotes: 1

Jezzamon
Jezzamon

Reputation: 1491

As I said in my comment, you need to use a callback.

I'm not too familiar with TweenLite, but can you add the onComplete callback to the last call only? Something like this:

for(var i:uint = 0; i < pointsArray.length; i++){
    var extraArguments:Object = {
        x:pointsArray[i].x,
        y:pointsArray[i].y,
        delay:i*.05,
        overwrite:false,
        onUpdate:updateHandler
    };
    // add in the onComplete callback only if it's the last loop.
    if (i == pointsArray.length - 1 ) {
        extraArguments.onComplete = yourOnCompleteFunction;
    }
    TweenLite.to(dot2, .05, extraArguments);
}

Upvotes: 0

Related Questions