How can I catch 2+ key presses at once?

你离开我真会死。 提交于 2020-01-03 17:32:51

问题


Well lately i got interested in creating JS games. (not an area i have experience with but it interests me).

i know there are several gaming engines for JS out there but i dont really want to create a game. rather i am curious on how things work / how can i create one.

I have several questions:

  1. Anyone with suggestions on where can I read about it? Prerequisite (what knowledge is needed).

  2. I tried making a small game of something walking in a rectangular. By binding keyup to the window and checking the event.which to get the key that was pressed. I realized that if i clicked on 2 buttons same time only 1 of them is being registered. how can i overcome that?

    $(window).keyup(function(event){
         globalEvent = event.which;
    
    });
    

回答1:


To directly answer your second question.

Here is one way:

var keyPressed = {};

$(window).keydown(function(e) {
    keyPressed[e.which] = true;
}).keyup(function(e) {
    keyPressed[e.which] = false;
});

Now you can use keyPressed whenever you want to determine if a key is down:

// wherever
var key1 = 65, key2 = 66; // A and B
if (keyPressed[key1] && keyPressed[key2]) {
    // A and B are both being pressed.
}



回答2:


In order to detect multiple keys being held down, use the keydown and keyup events.

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;
});

$(document).keyup(function (e) {
    delete keys[e.which];
});


来源:https://stackoverflow.com/questions/20962033/how-can-i-catch-2-key-presses-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!