Javascript multiple keys depressed

好久不见. 提交于 2019-12-13 13:05:00

问题


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.

Any ideas?


回答1:


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();



回答2:


I'd suggest you use an Array to hold key states.

var keyStates = [ ];

document.addEventListener('keydown', function(e) {
    keyStates.push( e.keyCode );
}, false);

document.addEventListener('keyup', function(e) {
    var pos = null;

    if( (pos = keyStates.indexOf( e.keyCode )) > -1 )
        keyStates.splice( pos, 1 );
}, false);

So with that, you can always check that array for keys currently beeing pushed.




回答3:


var currentKeyCodes=new Object();

function keyDown(e) {
    currentKeyCodes['x'+e.keyCode]=true;
}

function keyUp(e) {

    //Real check here
    if ((e.keyCode==39) && currentKeyCodes['x37']) {
        do_whatever_you_want();
    }

    //Housekeeping
    var s='x'+e.keyCode;
    if (currentKeyCodes[s]) currentKeyCodes[2]=false;
}


来源:https://stackoverflow.com/questions/8556085/javascript-multiple-keys-depressed

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