我如何在 as3 中激活多键

How can i active multi keybored in as3

我正在制作一个 运行ning 游戏,其中英雄将 运行,面对障碍物并通过跳跃和滑行继续障碍物。

现在英雄会 运行 当用户按下 D 并且它会保持 运行ning 直到一个固定点但是问题是一旦英雄开始 运行ning 另一个到按钮 W = jumpS = slide 不工作。

我希望这 2 个按钮在 hero 运行ning 时起作用。

这是我的代码

import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;

kim.gotoAndStop("hero Stand");

var dPressed:Boolean = false;
var aPressed:Boolean = false;
var jumping:Boolean = false;
var sPressed:Boolean = false;

stage.addEventListener(KeyboardEvent.KEY_DOWN , keyDownHandaler);
stage.addEventListener(KeyboardEvent.KEY_UP , KeyUpHandaler);
stage.addEventListener(Event.ENTER_FRAME , gameLoop);

function keyDownHandaler(Devent:KeyboardEvent):void
{
        if (Devent.keyCode == Keyboard.D )
            {
                dPressed = true;
            }

        else if (Devent.keyCode == Keyboard.S && !jumping && !sPressed)
            {
                sPressed = true;
            }
        else if (Devent.keyCode == Keyboard.W && !jumping && !sPressed)
            {
                jumping = true;
            }

function KeyUpHandaler (Uevent:KeyboardEvent):void 
{
    if (Uevent.keyCode == Keyboard.D)
        {
            //dPressed = false; (i commented this so that hero don't stop running)
            //hero.gotoAndStop("hero Stand");
        }

    else if(Uevent.keyCode == Keyboard.W)
    {
            jumping = false; 
            hero.gotoAndStop("heroStand");
    }

    else if(Uevent.keyCode == Keyboard.S)
    {
            sPressed = false;
            hero.gotoAndStop("hero Stand");
    }
}

function gameLoop(Levent:Event):void
{
    if (dPressed)
         {
        hero.x += 10;   
        hero.gotoAndStop("hero Run");
        }

    else if(jumping)
        {
             hero.y -= 15;
            hero.x += 10;
            hero.gotoAndStop("hero Jump");
        }

    else if(sPressed) {

            hero.x += 10;
            hero.gotoAndStop("hero Slide");
            }   
    }

因为您正在使用 else if 语句。相反,只需使用单独的 if 语句。 AS3 将根据需要读取 else if 逻辑块以找到真实条件,此时它执行该位代码,然后退出到 else if 的末尾语句,skiping everything after it. 如果你想测试所有条件(他 运行ning 吗?他在跳吗?他在滑吗?)其他按键,则只需使用 if 语句。使用 else if only when you want to reserve code to be 运行 only if the previous condition were false.

在你的情况下我想你只希望玩家在运行宁时能够滑动但不是 跳跃,对吧?所以它看起来像这样:

If (dPressed) {
    hero.x += 10;
    hero.goToAndPlay("hero run");
}
If (jumping) { // this code will run regardless of if dPressed is true
    hero.y -= 15;
}
else if (sPressed) { // this code will only be read if jumping is not true (you can't jump and slide at the same time)
    hero.goToAndStop("hero slide");
}

您必须同样更改您的其他逻辑语句。

我不会在键盘事件处理程序部分使用任何 else 语句。在我看来,最好让 AS3 始终检查按键的状态...处理 gameLoop 函数中的逻辑。