Javascript多个按键郁闷 [英] Javascript multiple keys depressed

查看:118
本文介绍了Javascript多个按键郁闷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以现在我正在使用一个函数,如果按下一个键,则将值设置为true,不管第一个键是否仍被按下,都会按下另一个键。

so right now I'm using a function that will set a value to true if one key being pressed, another being pressed regardless of whether or not the first one is still depressed.

 function doc_keyUp1(e) {
      if (e.keyCode == 37){
        lPunch = true 
      }
  }
  function doc_keyUp2(e) {
      if (e.keyCode == 39){
        rPunch = true
      }
  }
  document.addEventListener('keyup', doc_keyUp1, false)
  document.addEventListener('keyup', doc_keyUp2, false)

问题是,我希望能够确保如果第二个按键被按下,那么第一个按键必须仍然按下,这样有人就不能只按一个然后快速按下另一个按键似乎他们都被同时按下了。

The thing is, I want to be able to have it make sure that if the second key is being pressed, that the first one must still be down, so that someone can't just press one then the other quickly and make it seem as if they were both pressed down at the same time.

任何想法?

推荐答案

假设你有某种类似游戏循环的东西下面的工作(或者我应该说应该工作,因为我很长时间没有编写类似的东西,所以没有用当前的浏览器测试它 - 绝对习惯于工作):

Assuming you have some kind of "game loop" something like the following works (or perhaps I should say "should work", in that I haven't coded something like this for a long time and so haven't tested it with current browsers - definitely used to work):

var keyPressed = {};

document.addEventListener('keydown', function(e) {
   keyPressed[e.keyCode] = true;
}, false);
document.addEventListener('keyup', function(e) {
   keyPressed[e.keyCode] = false;
}, false);

function gameLoop() {
   if (keyPressed["39"] && keyPressed["37"]) {
      // do something (update player object state, whatever)
   }
   // etc
   // update display here
   setTimeout(gameLoop, 5);
}

gameLoop();

这篇关于Javascript多个按键郁闷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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