I'm trying to develop a JavaScript game engine and I've came across this problem:
- When I press SPACE the character jumps.
- When I press → the character moves right.
The problem is that when I'm pressing right and then press space, the character jumps and then stops moving.
I use the keydown
function to get the key pressed. How can I check if there are multiple keys pressed at once?
I used this way (had to check wherever is Shift + Ctrl pressed):
You should use the keydown event to keep track of the keys pressed, and you should use the keyup event to keep track of when the keys are released.
See this example: http://jsfiddle.net/vor0nwe/mkHsU/
(Update: I’m reproducing the code here, in case jsfiddle.net bails:) The HTML:
...and the Javascript (using jQuery):
In that example, I’m using an array to keep track of which keys are being pressed. In a real application, you might want to
delete
each element once their associated key has been released.Note that while I've used jQuery to make things easy for myself in this example, the concept works just as well when working in 'raw' Javascript.
If one of keys pressed is Alt / Crtl / Shift you can use this method: