如何通过AS3在3个对象之间建立交换(随机)位置?

时间:2016-08-19 10:46:22

标签: actionscript-3

//array
var boxs: Array = new Array 
boxs[0] = [b1.x = 307.95  , b1.y = 202]
boxs[1] = [b2.x = 233.95  ,  b2.y = 202]
boxs[2] = [b3.x = 159.95  ,  b3.y = 202]

//varable 
var oldg:Number = 0
//random number
oldg = Number(Math.floor(Math.random()*boxs.length))

1 个答案:

答案 0 :(得分:1)

天真的方法:

    public function Main()
    {
        const array:Array = [1,2,3,4,5,6,7];
        trace(array);
        // 1,2,3,4,5,6,7
        swapTwoRandomElements(array);
        trace(array);
        // 1,2,3,6,5,4,7
    }

    private function swapTwoRandomElements(input:Array):void
    {
        const indices:Array = [];
        for (var i:int = 0; i < input.length; i++)
        {
            indices.push(i);
        }
        const indexFirst:int = indices[int(Math.random() * indices.length)];
        indices.splice(indexFirst, 1);
        const indexSecond:int = indices[int(Math.random() * indices.length)];
        indices.splice(indexSecond, 1);

        const tmp:* = input[indexFirst];
        input[indexFirst] = input[indexSecond];
        input[indexSecond] = tmp;
    }