简体   繁体   English

选择Array Actionscript 3的随机元素

[英]Pick random Element of an Array Actionscript 3

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 感谢您的时间

You can get a random number using Math.random() This will return a number between 0 and 1. 您可以使用Math.random()获取一个随机数。这将返回0到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];
}

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. 如果您已经有一个Array ,您应该能够定义一个随机排序,然后您可以根据需要将它们添加到舞台。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM