# As3 Random movieclips from an array to the stage

For a game with orders and clients I was trying to create the following situation:

Every half minute, a client should appear at the counter. In this case I have an array with 4 movieclips (4 clients). After 30 seconds I want the first randomly choosed client to appear at the counter (y = 200). This is my solution (wich obviously isn't the right way, forgive me):

    var timer:Timer = new Timer(1000);
var elapsedTime:Number = 0;

timer.start();

function displaytime(event:TimerEvent):void
{
elapsedTime++;
counterDisplay.text = String(elapsedTime);
}

if(elapsedTime == 30){

for (var i:uint = 0; i < mcArray.length; i++) {

mcArray[i].x = Math.floor( Math.random()*(stage.stageWidth) );
mcArray[i].y = 200;

}

}


My question to you is: What am I doing wrong, and how can I accomplish this? Thanks in advance!

edit:I'm slightly unclear on the question but I think this is the answer?

I would ditch the timer altogether and just use an enter-frame event listener.

var playerArr:Array=[];
var t:int=0;
public function Main(){
}

function tick(){

t++;

if (t%900==1){
spawnUnits(3)
}
}

//If you were spawning Characters for the first time
function spawnUnits(numUnits:int){
for(i=0;i<=numUnits;i++){
newSpawn:MovieClip=new *CLASSNAME*
newSpawn.x=Math.Random()*400;
newSpawn.y=200;
playerArr.push(newSpawn);
}
}

//If you were grabbing previously spawned Characters and moving them you would
//Call this function instead of spawnUnits

function characterMover(){
var moveChar:Object=playerArr[(Math.Random()*playerArr.length)-1];
moveChar.x=Math.Random()*400;
moveChar.y=200;
//then if they weren't already on the display list you could add them here

}

• :Thank you for your answer, I can't give the clients the same class name, so can you tell me what you mean by newSpawn:MovieClip=new CLASSNAME – Opoe Mar 11 '12 at 10:35
• Just take the type of object you want to spawn as a parameter of the array: function spawnUnits(CLASSNAME,numUnits) then in the function say newSpawn=new CLASSNAME; – Zee Bashew Mar 11 '12 at 19:13

Well first off you loop through the entire array, when you only want one customer. If you only want, say, mcArray[2] then only manipulate that value, don't loop through the entire array.

More generally however, it looks like you are writing the code outside of any function, which doesn't make any sense in this case and even in situations where it works it is a really bad idea. Whatever you're doing on the timer has to be inside the timer function.