开发者

Add/Tween/Remove - Multiple instances of the same MC (Tweenlite)

开发者 https://www.devze.com 2022-12-10 23:38 出处:网络
I\'m trying to create a simple loop that adds a random number of stars, fades them out and removes them.

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 开发者_StackOverflow中文版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!


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);
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号