2016-02-19 106 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);