0

我的 switch 语句有点挣扎(我以前从未使用过 switch)。当我的对象到达舞台的顶部或底部时,我进行了命中测试。发生这种情况时,我想切换状态(有问题的游戏是一个简单的平台游戏,允许玩家在碰到新表面时切换重力。下面是我当前的代码:

{
    ...

    if(player.hitTestObject(bottom)) {
        //Switch state to normal
    }
    if(player.hitTestObject(top)) {
        //Switch state to inverted
    }
}

switch (myGrav){
    case "NORMAL":
        trace("Normal")
        player.gotoAndPlay(1);
        oktoJump = false;
        player.y = 376.5;

    case "INVERTED":
        trace("Inverted")
        player.gotoAndPlay(8);
        oktoJump = false;
        player.y = 12;
}

谢谢!

4

2 回答 2

2

switch 语句中的 case 缺少break; 因此,代码将通过 switch 语句继续执行。

这应该是:

var myGrav:String = "NORMAL";

if (player.hitTestObject(bottom))
    myGrav = "NORMAL";

if (player.hitTestObject(top))
    myGrav = "INVERTED";

switch (myGrav)
{
    case "NORMAL":
        trace("Normal")
        player.gotoAndPlay(1);
        oktoJump = false;
        player.y = 376.5;
        break;

    case "INVERTED":
        trace("Inverted")
        player.gotoAndPlay(8);
        oktoJump = false;
        player.y = 12;
        break;
}
于 2012-11-27T22:50:30.687 回答
1

当我可以摆脱它时,我更喜欢更少的变量。

switch (true){
    case (player.hitTestObject(bottom)):
        trace("Normal")
        player.gotoAndPlay(1);
        oktoJump = false;
        player.y = 376.5;
        break;

    case (player.hitTestObject(top)):
        trace("Inverted")
        player.gotoAndPlay(8);
        oktoJump = false;
        player.y = 12;
        break;
}
于 2012-11-28T14:04:51.647 回答