如何一次抓住2个以上的按键? [英] How can I catch 2+ key presses at once?

查看:79
本文介绍了如何一次抓住2个以上的按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我对创建JS游戏感兴趣。 (不是我有经验但我感兴趣的地区)。

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

我知道JS有几个游戏引擎,但我真的不想创造一个游戏。相反,我很好奇如何工作/如何创建一个。

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.

我有几个问题:


  1. 任何人都有关于我在哪里可以阅读的建议吗?先决条件(需要什么知识)。

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

我尝试用长方形走路的小游戏。通过将keyup绑定到窗口并检查 event.which 来获取按下的键。我意识到,如果我同时点击2个按钮,其中只有1个正在注册。我怎么能克服这个?

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;

});



推荐答案

直接回答你的第二个问题。

To directly answer your second question.

这是一种方式:

var keyPressed = {};

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

现在你可以随时使用 keyPressed 确定密钥是否已关闭:

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个以上的按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆