2016-02-19 62 views
-1

我写了一个小动作,基本上讲一个影片剪辑去播放列表中的随机帧。这里是代码:as3防止连续两次选择随机帧标签

function getRandomLabel(): String { 

    var labels: Array = new Array("e1", "e2", "e3"); 
    var index: Number = Math.floor(Math.random() * labels.length); 
    return labels[index]; 
} 
mc.gotoAndStop(getRandomLabel()); 

我想解决的问题是防止同一个随机帧标签被连续选中两次。

回答

0

我的建议是洗牌阵列的每个n调用getRandomLabeln作为labels数组的长度。在洗牌时,确保最近使用的标签不是阵列中的第一个项目。

// this array can be of any length, and the solution should still work 
var labels:Array = ["e1","e2","e3"]; 
var count:int = labels.length; 
labels.sort(randomSort); 

function getRandomLabel(): String { 
    count--; 

    var randomLabel:String = labels.shift(); 
    labels.push(randomLabel); 

    // when the counter reaches 0, it's time to reshuffle 
    if(count == 0) 
    { 
     count = labels.length; 

     labels.sort(randomSort); 
     // ensure that the next label isn't the same as the current label 
     if(labels[0] == randomLabel) 
     { 
      labels.push(labels.shift()); 
     } 
    } 

    return randomLabel; 
} 

// this function will "shuffle" the array 
function randomSort(a:*, b:*):int 
{ 
    return Math.random() > .5 ? 1 : -1; 
} 
1

如果你想要做的就是确保当前帧标签不是从列表中选择你能做到这一点,只需从阵列筛选出当前标签:

function getRandomLabel(currentLabel:String):String { 
    var labels:Array = ["e1", "e2", "e3"]; 
    var currentIndex:int = labels.indexOf(currentLabel); 
    if (currentIndex > -1) 
     labels.splice(currentIndex, 1); 
    var index:Number = Math.floor(Math.random() * labels.length); 
    return labels[index]; 
} 

mc.gotoAndStop(getRandomLabel(mc.currentLabel)); 

实际上,如果您要做的只是去任意除当前帧标签外,您可以使用MovieClip/currentLabels并使其成为任何MovieClip的可重用功能:

function gotoRandomFrameLabel(mc:MovieClip):void { 
    var labels:Array = mc.currentLabels.filter(function(frame:FrameLabel, ...args):Boolean { 
     return frame.name != mc.currentLabel; 
    }); 
    var index:int = Math.random() * labels.length; 
    mc.gotoAndStop(labels[index].frame); 
} 

gotoRandomFrameLabel(mc); 
gotoRandomFrameLabel(other_mc);