我试图开发一个JavaScript游戏引擎,我遇到了这个问题:

当我按空格键时,角色会跳跃。 当我按下→角色向右移动。

问题是,当我按右键,然后按空格键时,角色会跳跃,然后停止移动。

我使用keydown函数来按下键。如何检查是否同时按下了多个键?


当前回答

这不是一个通用的方法,但在某些情况下是有用的。这是有用的组合,如CTRL + something或Shift + something或CTRL + Shift + something,等。

示例:当您想使用CTRL + P打印页面时,第一个按下的键总是CTRL + P, CTRL + S, CTRL + U和其他组合也是如此。

document.addEventListener (keydown,函数(e) { //SHIFT +某个值 如果(e.shiftKey) { 开关(e.code) { 例“钥匙”: console.log('Shift + S'); 打破; } } //CTRL + SHIFT +一些 如果(e。&& e.shiftKey){ 开关(e.code) { 例“钥匙”: console.log('CTRL + Shift + S'); 打破; } } });

其他回答

如果有人需要简单的解决方案。

let keys = [];
document.addEventListener("keydown", (e) => {
  keys.push(e.key);
  if (keys.includes("Control") && keys.includes("o")) {
    console.log("open");
  }

  if (keys.includes("Control") && keys.includes("s")) {
    console.log("save");
  }
});

// clear the keys array
document.addEventListener("keyup", () => {
  keys = [];
});

这不是一个通用的方法,但在某些情况下是有用的。这是有用的组合,如CTRL + something或Shift + something或CTRL + Shift + something,等。

示例:当您想使用CTRL + P打印页面时,第一个按下的键总是CTRL + P, CTRL + S, CTRL + U和其他组合也是如此。

document.addEventListener (keydown,函数(e) { //SHIFT +某个值 如果(e.shiftKey) { 开关(e.code) { 例“钥匙”: console.log('Shift + S'); 打破; } } //CTRL + SHIFT +一些 如果(e。&& e.shiftKey){ 开关(e.code) { 例“钥匙”: console.log('CTRL + Shift + S'); 打破; } } });

我会试着在按键时添加一个按键事件处理程序。例句:

window.onkeydown = function() {
    // evaluate key and call respective handler
    window.onkeypress = function() {
       // evaluate key and call respective handler
    }
}

window.onkeyup = function() {
    window.onkeypress = void(0) ;
}

这只是为了说明一个模式;这里我就不详细介绍了(尤其是浏览器特定的level2+事件注册)。

请回复这是否有帮助。

如果你想找到任何按键事件与控制键,你可以这样做

onkeypress = (e) =>{
console.log(e);
if(e.ctrlKey && e.code == "KeyZ"){
    document.write("do somthing")
} }
Easiest, and most Effective Method

//check key press
    function loop(){
        //>>key<< can be any string representing a letter eg: "a", "b", "ctrl",
        if(map[*key*]==true){
         //do something
        }
        //multiple keys
        if(map["x"]==true&&map["ctrl"]==true){
         console.log("x, and ctrl are being held down together")
        }
    }

//>>>variable which will hold all key information<<
    var map={}

//Key Event Listeners
    window.addEventListener("keydown", btnd, true);
    window.addEventListener("keyup", btnu, true);

    //Handle button down
      function btnd(e) {
      map[e.key] = true;
      }

    //Handle Button up
      function btnu(e) {
      map[e.key] = false;
      }

//>>>If you want to see the state of every Key on the Keybaord<<<
    setInterval(() => {
                for (var x in map) {
                    log += "|" + x + "=" + map[x];
                }
                console.log(log);
                log = "";
            }, 300);