Search code examples
actionscript-3flashtweenremovechild

Movieclips freeze during tween


I've written this thing that displays little star graphics randomly, tweens them down the screen, and then removes them. I'm having a problem though where after maybe 10 seconds some of the stars freeze in place mid tween and then just stay there.

Here's my code:

// Create Random Variables.
var xPosition:int;
var yPosition:int;

// Animate Stars.
function stars ():void {
//Defines random starting position for stars.
xPosition = Math.floor(Math.random()*(540))+5;
yPosition = Math.floor(Math.random()*(2))+5;

//Add and position stars.
var newStar:star = new star();
newStar.x = xPosition;
newStar.y = yPosition;
addChild(newStar);

//Tween stars.
var tweenStar:Tween = new Tween(newStar, "y", None.easeOut, yPosition, stage.stageHeight, 4, true);

//Event listener checks star tween.
tweenStar.addEventListener(TweenEvent.MOTION_FINISH, removeStar);

//Remove stars when tween is complete.
function removeStar(e:TweenEvent):void {
    removeChild(newStar);
            tweenStar.removeEventListener(TweenEvent.MOTION_FINISH, removeStar);
}
}

Solution

  • Your tweens are being picked up by the garbage collector, what you need to do is create a global array to store your tweens after you create them so the garbage colletor does not get them.

    var tweens:Array = [];
    

    and then add tweens to it

    var tweenStar:Tween = new Tween(newStar, "y", None.easeOut, yPosition, stage.stageHeight, 4, true);
    tweens.push(tweenStar)
    

    Also if possible use TweenLite, it's a lot better then Adobe's standard tween, and you won't have to worry about losing tweens to the garbage collector.