AS3中If语句中的事件监听器

时间:2014-04-08 02:53:10

标签: actionscript-3 flash

我有一个(也许很奇怪)问题,你经验丰富的ActionScript专家: 逻辑上也许我错过了一些东西,但情况如下:我有嵌套在MovieClip的不同帧上的按钮和MovieClip的附加类我有一个if语句,为嵌套在适当帧上的按钮添加一个事件监听器;但是,当我运行代码时,无论运行所述代码的条件是否为真,闪存似乎都按顺序执行代码。我只是好奇是否有更好的方式处理这种情况?

public function Die1() {
    // constructor code
trace("Roll 1 D1 is:", MainGame.valueRoll1);

if (MainGame.valueRoll1 == 1){
    gotoAndStop(1);
    die1Sd1_btn.addEventListener(MouseEvent.CLICK, Side1process);
}

if (MainGame.valueRoll1 == 2){
    gotoAndStop(2);
    die1Sd2_btn.addEventListener(MouseEvent.CLICK, Side2process);
}

if (MainGame.valueRoll1 == 3){
    gotoAndStop(3);
    die1Sd3_btn.addEventListener(MouseEvent.CLICK, Side3process);
}

if (MainGame.valueRoll1 == 4){
    gotoAndStop(4);
    die1Sd4_btn.addEventListener(MouseEvent.CLICK, Side4process);
}

if (MainGame.valueRoll1 == 5){
    gotoAndStop(5);
    die1Sd5_btn.addEventListener(MouseEvent.CLICK, Side5process);
}

if (MainGame.valueRoll1 == 6){
    gotoAndStop(6);
    die1Sd6_btn.addEventListener(MouseEvent.CLICK, Side6process);
}
}

感谢所有回复此帖的人,我想世界上所有的语法知识对程序逻辑无能为力......

1 个答案:

答案 0 :(得分:0)

您最好在整个裸片上使用单个事件侦听器,而不是使用大量依赖于裸片当前帧的侦听器。像这样:

function Die() {
    this.addEventListener(MouseEvent.CLICK,processDie);
}
// instead of that entire 'if'! 
// Also, this approach will allow you making more dies without spawning classes
function processDie(e:MouseEvent):void {
    switch (currentFrame) {
        case 1: side1Process(); break;
        case 2: side2Process(); break;
        case 3: side3Process(); break;
        case 4: side4Process(); break;
        case 5: side5Process(); break;
        case 6: side6Process(); break;
    }
}

MainGame中,您确实喜欢这样:

var dice:Array=[];
public function MainGame {
    for (var i:int=0;i<maxDice;i++) {
        var die:Die=new Die();
// make a new die. It'll automatically have an event listener attached
        die.x=i*50;
        die.y=20; // place somewhere
        addChild(die);
        dice.push(die);
    }
    // rest of code follows
}

然后,当你必须掷骰子时,你会这样做:

for (var i:int=0;i<dice.length;i++) 
    if (mayIRollTheDie(i)) // provide a correct condition here
        dice[i].gotoAndStop(1+Math.floor(Math.random()*6));

然后你的骰子会根据1-6的卷数改变帧数。他们的currentFrame属性将反映滚动,因此您可以轻松收集它们。并且您将不再需要收听Event.FRAME_CONSTRUCTED,因为现在所有内容都与当前帧的对象分离。