首页 > 解决方案 > 如何在不重复的情况下在数组中生成对象?

问题描述

我有 MC rockThrowers 被添加到舞台的 3 个不同位置。它们使用运行良好的随机生成器随机生成。用户单击舞台上的一个按钮,然后将其添加到rockThrowers舞台并推入他们自己的数组aRockThrowerArrayrockThrowers在空位上添加一个新的。我尝试了不同的策略,主要是布尔值,并将它们从他们自己的类调用到我的主类,但似乎没有任何效果。这是我的

rockThrowers 类:

    private function startPosition():void 
    {
        // y position 
        this.y =  (stage.stageHeight / 2) + 200;

        //Start Speed
        nSpeed = randomNumber(5, 8);

        leftScreenSpawn = randomNumber(1, 3);


        //For Left Screen
        leftNeg =  (stage.stageWidth / 2) - 200;
        leftMiddle =  (stage.stageWidth / 2) - 150;
        leftPos =  (stage.stageWidth / 2) - 100;



        //Left Screen
        if (leftScreenSpawn == 1)
        {
            this.x = leftNeg;
            bLeftNeg = true; // Now if the left Rock thrower is destroyed then turn back to false on main engine class
        }else
        if (leftScreenSpawn == 2)
        {
            this.x = leftMiddle;
            bLeftMiddle = true;
        }else
        if (leftScreenSpawn == 3)
        {
            this.x = leftPos;
            bLeftPos = true;
        }



        //Move 
        startMoving();
    }

现在在我的主类中,当用户单击左屏幕 Btn 时,我已经设置了这样的设置:

    private function rockThrowerSpawn(e:MouseEvent):void 
    {
        //Instantiate screens before hand
        rockThrowerSpawnScreen.x = (stage.stageWidth / 2);
        rockThrowerSpawnScreen.y = (stage.stageHeight / 2) + 200;
        addChild(rockThrowerSpawnScreen);

        rockThrowerSpawnScreen.left.addEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);

    }

然后是 Spawn 函数:

private function chooseSpawnSideRockThrowers(e:MouseEvent):void 
    {
        if (e.currentTarget == rockThrowerSpawnScreen.left) // Spawn LEFT
        {

            //add new rock thrower
             rockThrowers = new mcRockThrowers();
             //Add object
             addChild(rockThrowers);
             //Add to Array
             aRockThrowerArray.push(rockThrowers);
             //trace("LEFT SPAWN");

        }

        //Subtract resources and update text
        nResources -= 10;
        updateResourceTextField();


        //Remove Listeners
        rockThrowerSpawnScreen.left.removeEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);
        rockThrowerSpawnScreen.destroy();
    }

我知道仅此一项总是会产生随机位置我删除了所有不起作用的东西现在我回到了这个正方形。关于我如何做到这一点的任何想法?感谢所有支持。

标签: actionscript-3adobeflashdevelop

解决方案


简单的。您需要一个以随机顺序生成 3 个值的有限数组。

var L:Array =
[
    (stage.stageWidth / 2) - 200,
    (stage.stageWidth / 2) - 150,
    (stage.stageWidth / 2) - 100,
];

function fetchPosition():Number
{
    // Get a random index based on the current length of L.
    var anIndex:int = Math.random() * L.length;

    // Record the result.
    var result:Number = L[anIndex];

    // Remove the result from the list.
    L.splice(anIndex, 1);

    return result;
}

因此,您可以在每次应用程序运行时有效地调用fetchPosition()三次,并且每次运行L的内容都将以随机顺序获取,更重要的是,您不会两次获得相同的值,因为获取的值已从数据集。


推荐阅读