7

I have an array of movieclips and i want to put them on stage. so they have to be unique and randomly chosen.

how can I do that?

thank you for your time

2 Answers 2

9

You can get a random number using Math.random() This will return a number between 0 and 1.

So, for getting a random element of the array, use this:

function getRandomElementOf(array:Array):Object {
    var idx:int=Math.floor(Math.random() * array.length);
    return array[idx];
}
Sign up to request clarification or add additional context in comments.

10 Comments

hi, thank you for the answer, but how can I put them on the satge? i have tried with addChild(array[idx]) but is not working;
stage.addChild(getRandomElementOf(movieClipArray)); or stage.addElement(getRandomElementOf(movieClipArray));
You will need to have already set the x and y properties of the movieclips before adding (or you can even do it after adding)
i have the x and y of the mc`s var min_x:Number = stage.x - 2 * (breite / 4) - 50; var max_x:Number = stage.x - (breite / 4) - 50; var mid_x:Number = stage.x - 50; var min_y:Number = 0; var max_y:Number = hoehe / 2; var mid_y:Number = hoehe; var n:uint = array1.length; for (var i:uint = 0; i < n; i++) { var mc:MovieClip = array1[i]; mc.x = Math.round(Math.random() * (max_x - min_x) + min_x); mc.y = Math.round(Math.random() * (max_y - min_y) + min_y); }
It works perfectly... I have tried using addChild and it is all fine
|
1

If you have an Array already, you should be able to define a random sort, then you can add them to the stage as needed.

//get your array as needed...
var myArray:Array = getYourMovieClipsArray();

//randomize it by "sorting" it...
myArray.sort(randomSort);

//do something with them...
for(var i:int=0;i<myArray.length;i++){
    addChild(myArray[i]);
}



//sorting function
public function randomSort(objA:Object, objB:Object):int{
    return Math.round(Math.random() * 2) - 1;
}

2 Comments

why to sort and re-arrange array when you can just get a random index ?
I presumed the comment about "unique" in the OP's question indicated he wanted to ensure that the clips were not pulled out multiple times. If desired, you could create an array of indexes to match the movie clip array... randomize the array of indexes... then pluck from the randomized list 1 at a time until finished to ensure no duplicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.