Javascript multiple keystrokes

so right now I'm using a function that will set to true if one key is pressed, the other is pressed, regardless of whether the first one is pressed.

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 fact is that I want him to make sure that if the second key is pressed, the first one should still be down, so that someone could not just quickly press one and then the other, and make it seem like they are pressed together to friend.

Any ideas?

+6
source share
3 answers

Assuming you have some kind of “game loop”, something like the following works (or maybe I should say “should work”, in the sense that I have not coded something like this for a long time and therefore not 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(); 
+6
source

I would suggest you use Array to store 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); 

This way you can always check that the array is for the keys that are currently running.

+2
source
 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; } 
+2
source

Source: https://habr.com/ru/post/904046/


All Articles