简体   繁体   中英

how to check if a key is pressed after pressing two keys and releasing the second in javascript?

I'm trying to build a simple game using javascript , the character is supposed to move ahead and turn to the right by pressing respectively the up arrow and the right arrow keys.


the problem is when I press 'up' then 'right' the character moves forward then turn to the right and keeps moving diagonally, but when I release the right arrow key it stops moving while I want it to keep moving forward, apparently the "keydown" event can't recognize anymore that the up arrow key is still pressed.So how can I solve it?


code:

var keys = [];

key down event :

   document.body.addEventListener("keydown",(event) => {

        keys[event.keyCode] = true;
        keysProcess();  //this function loops through the array and moves the character depending on the keyCode value 
    });

key up event:

    document.body.addEventListener("keyup",(event) =>{

        keys[event.keyCode] = false ; 
        keysProcess();

    }); 

A quick check under windows 10 shows it only automatically repeats the last key pressed.

EG If you hold down the left arrow key it repeats, as you would expect. If you then press the right arrow, without releasing the left arrow, the right arrow repeats. If you then release the right arrow, still holding the left arrow key down, the left arrow does NOT resume being automatically repeated.

So if you want the a key to resume repeating after another key is released, you would need to design and introduce timing code using, say, setInterval to programmatically repeat keys that are being held down after key down is received for a different key. Obviously if a key up event is received for a key being repeated by timer, repeating it with the timer needs to cease.

How important it is for a key to resume repeating is for you to judge - remember if you can't fix a bug or it's too expensive to fix, call it a feature and tell everyone about it. You wouldn't be the first :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM