Select a random element in an ActionScript 3 array

I have an array of movie clips, and I want to put them on stage. therefore, they must be unique and random.

How can i do this?

Thank you for your time.

+7
source share
2 answers

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

So, to get a random array element, use this:

 function getRandomElementOf(array:Array):Object { var idx:int=Math.floor(Math.random() * array.length); return array[idx]; } 
+8
source

If you already have an Array , you can define a random sort, then you can add them to the scene 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; } 
0
source

All Articles