Question

I'm trying to create a simple loop that adds a random number of stars, fades them out and removes them.

The script I've come up with does everything but remove them, and perhaps I need a less on adding children to a stage.

Here's what I come up with

import flash.display.*;
import com.greensock.*;
import com.greensock.easing.*;

// timer setup
var timer:Timer=new Timer(randomNumber(500,1000));
timer.addEventListener(TimerEvent.TIMER,run_stars);
timer.start();

// Random number generator
function randomNumber(low:Number=NaN, high:Number=NaN):Number {
  var low:Number = low;
  var high:Number = high;
  if(isNaN(low)) { throw new Error("no low number"); }
  if(isNaN(high)) { throw new Error("no high number"); }
  return Math.round(Math.random() * (high - low)) + low;
}

// randomly adding stars on timer
function run_stars(event:TimerEvent):void {
    // random num of stars
    for (var i:Number=1; i<=randomNumber(2,7);i++) {

            var star:m_star = new m_star();
            addChild(star);

            // This is where my problem starts, I'm adding the same movie clip multiple times without any way to identify and remove. 


            star.x = randomNumber(0, stage.stageWidth);
            star.y = randomNumber(0,stage.stageHeight/2);

            TweenLite.to(star, randomNumber(0.5,1), {alpha:0.25, onComplete:removeStar()});

    }

    timer.delay = randomNumber(500,1000);
    timer.start();
}

function removeStar() {
    removeChild(star);
    //this would be where I attempt to remove a star but because they aren't unique it will never work, and the star movie clip is called inside of the function so it cant even see it. 
    }

stop();

I need a way to make the movie clips unique so I can tell my oncomplete function to remove the property clip, if I don't do this the movie will eventually slow down and crash because of so many (invisible) movieclips.

Thanks!

Was it helpful?

Solution

Pass the MovieClip as a parameter of the onComplete function:

TweenLite.to(star, randomNumber(0.5,1), {
    alpha:0.25,
    onComplete:removeStar, 
    onCompleteParams:[star]
});

function removeStar(mc:MovieClip):void
{
    if (contains(mc))
    {
        removeChild(mc);
    }
}

OTHER TIPS

Noticed a bug here:

for (var i:Number=1; i<=randomNumber(2,7);i++) {

That's going to call for a random number between 2 and 7 each time it goes through the loop. You will have a skew towards 1 or 2 stars rather than 5 or 6. (reduced by 1 from the value in the passed from randomNumber because you start your index at 1 not 0) I imagine you don't mean to do that?

var len:int = randomNumber(2, 7);
for (var i:int = 1; i <= len; i++) {

is probably closer to working how you intended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top