Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multiple keys depressed

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?

like image 901
Riveascore Avatar asked Dec 19 '11 00:12

Riveascore


1 Answers

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();
like image 100
nnnnnn Avatar answered Oct 22 '22 10:10

nnnnnn