在HTML5 / Javascript中一次按多个键

时间:2018-03-19 13:06:50

标签: javascript html5

我试图编写一个游戏,其中玩家控制的角色可以移动并拍摄东西,问题是,如果我按下射击键他会停止行走,因为一次只能注意到一个键。

如何制作,以便一次使用多个键。 我对代码很新,所以我可能听不懂令人困惑的概念。 感谢

function move(e){

//alert(e.keyCode);
if(e.keyCode==68){
if(over == 0){
if(xPos < 990){
    xPos+=10;

}
}
}


if(e.keyCode==65){
if(over == 0){
if(xPos > 0){
    xPos-=10;
}
}   
}


if(e.keyCode==87){
if(over < 1){
if(yPos > 0){

    yPos-=10;
}
}
}


if(e.keyCode==83){
if(over == 0){
if(yPos < 540){

    yPos+=10;
}

}   
}

} document.onkeydown = move;

2 个答案:

答案 0 :(得分:0)

您可以尝试制作一个对象来存储密钥

var keys = {};
document.onkeydown = function(evt) {
    keys[evt.keyCode] = true;
    move();
};
document.onkeyup = function(evt) {
    delete keys[evt.keyCode];
};

function move() {
// alert(e.keyCode);
if (keys[68]) {
    if (over == 0) {
        if (xPos < 990) {
            xPos += 10;

        }
    }
}
if (keys[65]) {
    if (over == 0) {
        if (xPos > 0) {
            xPos -= 10;
        }
    }
}
if (keys[87]) {
    if (over < 1) {
        if (yPos > 0) {

            yPos -= 10;
        }
    }
}
if (keys[83]) {
    if (over == 0) {
        if (yPos < 540) {
            yPos += 10;
        }
    }
}

答案 1 :(得分:0)

这就是你的代码的样子:

&#13;
&#13;
var over, xPos, yPos;


var keysPressed = {};

function move(e) {
  keysPressed[e.keyCode] = true;
  console.log(keysPressed);
  if (keysPressed[68]) {
    if (over == 0) {
      if (xPos < 990) {
        xPos += 10;

      }
    }
  }


  if (keysPressed[65]) {
    if (over == 0) {
      if (xPos > 0) {
        xPos -= 10;
      }
    }
  }


  if (keysPressed[87]) {
    if (over < 1) {
      if (yPos > 0) {

        yPos -= 10;
      }
    }
  }


  if (keysPressed[83]) {
    if (over == 0) {
      if (yPos < 540) {

        yPos += 10;
      }

    }
  }
}
document.onkeydown = move;
document.onkeyup = function(e) {
  delete keysPressed[e.keyCode];
};
&#13;
&#13;
&#13;