actionscript 3,gotoandstop随机帧出了下3

时间:2012-11-07 14:52:34

标签: flash actionscript random frame

所以在我的闪光灯上,我有部分你可以选择哪种方式选择,你选择的那条路应该随机化,我试图建立它,以便当用户选择一条路时,他被扔进去随机抽取3个标记框架中的一个,我甚至考虑将一些随机化部分添加到最不可能发生的道路上。

    stop();

road1a.addEventListener(MouseEvent.CLICK, firstroadA);

function firstroadA(e:MouseEvent):void{
    if(this.currentFrame == 9){
        var randomNumber:Number = Math.floor(Math.random()*3)
        if (randomNumer == 0){
            gotoAndStop(10);
        }
        if (randomNumber == 1){
            gotoAndStop(11);
        }
        if (randomNumber == 2){
            gotoAndStop(12);
        }
    }
    else{
        nextFrame();
    }

}

在这个测试中,我试图这样做,以便用户的选择发生在第9帧,当他选择点击firstroadA时,他会去一些随机帧,10,11或12 ......所以,我希望我已经足够清楚; 我的问题简而言之,我如何随机化gotoAndStop帧,以及如何添加一些罕见的帧,这些帧很少被选择到gotoAndStop ....谢谢!

1 个答案:

答案 0 :(得分:0)

您可以根据需要使用加权随机数。看看这段代码吧,它可以随心所欲:

stop();

gotoAndStop(9);

road1a.addEventListener(MouseEvent.CLICK, firstroadA);

function firstroadA(e:MouseEvent):void
{
    if(this.currentFrame == 9)
    {
        // These are the weight chance for each "road"
        // I used 30%, 50%, and 10% arbitrarily
        var choiceWeights:Array = [30, 50, 10];

        // frame choices
        var roadFrames = [10, 11, 12];

        // get a weighted random
        var r:int = makeChoiceWithWeight(choiceWeights);

        //go to the selected frame
        gotoAndStop(roadFrames[r]);
    }
    else
    {
        nextFrame();
    }
}

function makeChoiceWithWeight(choiceWeights:Array):int
{
    var sumOfWeights:int = 0;
    var numWeights:int = choiceWeights.length;

    // add all weights
    for(var i:Number = 0; i < numWeights; i++) sumOfWeights += choiceWeights[i];

    // pick a random number greater than zero and less than the total of weights
    var rnd:Number = Math.floor(Math.random()*sumOfWeights);

    //keep reducing the random number until less than a choices weight
    for(var ii:Number = 0; ii < numWeights; ii++)
    {
        if(rnd < choiceWeights[ii]) return ii;

        rnd -= choiceWeights[ii];
    }

    // should never reach this point
    return 0;
}

要深入了解加权随机数,请查看此SO答案: Weighted random numbers