0

so I'm creating a project and for the background I want stars randomly appearing and dissapearing from the screen.

I have the stars randomly appearing, but they just stay on the screen and eventually fill the whole screen with stars. I would like for it to start removing 1 star and add another when there is 100 stars on screen. or even for there to be 100 stars on screen at the beginning and the timer just removes and adds 1 star each time.

So I am adding mystar randomly on the stage at random times, just need to get 1 removed, at the same time as they are being added so they do not completely cover my screemn.

var myTimer:Timer = new Timer(2,0 );
var randNum = Math.round( 500 + Math.random() * 4000 );
myTimer.addEventListener(TimerEvent.TIMER, fasttimerListener);

function fasttimerListener (e:TimerEvent):void{

var timerObj:Timer = e.target as Timer;
randNum = Math.round( Math.random() * 100 );
timerObj.delay = randNum;

var mystar:smallstar = new smallstar();
mystar.x = Math.random() * stage.stageWidth;
mystar.y = Math.random() * stage.stageHeight;
addChild(mystar);

}

myTimer.start();

please help, I think I might have to use an array? but not great at as3. thanks in advance.

1 Answers1

0

Here is the code I came up after trying to solve your problam, and yes I used Array:

var myTimer:Timer = new Timer(2,0 );
var randNum = Math.round( 500 + Math.random() * 4000 );

var starsCount:int = 100; //stars number in stage  

var st:int=0; //star inde number in Array


//---------------------------------------------------------------
//creating an Array of 100 mc stars
//---------------------------------------------------------------
var starsArray:Array=[];  //Array of movieclips smallstar

//using for loop to create 100 stars and put them in Array
for(var star:int=0; star<starsCount; star++){ 
    var mystar:smallstar = new smallstar();

    //puts mc smallstar on Array
    starsArray.push(mystar);
}


myTimer.addEventListener(TimerEvent.TIMER, fasttimerListener);

function fasttimerListener (e:TimerEvent):void{

var timerObj:Timer = e.target as Timer;
randNum = Math.round( Math.random() * 100 );
timerObj.delay = randNum;

starsArray[st].x = Math.random() * stage.stageWidth;
starsArray[st].y = Math.random() * stage.stageHeight;
addChild(starsArray[st]);
st++; //changing star index on array

//doesnt let st to be bigger than Array length
if (st>=starsArray.length) st = 0; 
}

myTimer.start();

Hope it helps.