Reputation: 71
I'm working on an HTML5 Javascript 2D game. I need to handle user input to move the character on the canvas. I wrote a piece of code to handle a "key pressed" state.
const PRESSED = 1;
const RELEASED = 0;
const UP = 90;
const DOWN = 83;
const LEFT = 81;
const RIGHT = 68;
['keyup', 'keydown'].forEach(eventName => {
window.addEventListener(eventName, function(e){
e.preventDefault();
const keyState = e.type === 'keydown' ? PRESSED : RELEASED;
const keyCode = e.keyCode;
if(keyCode === UP){
player.go.dirY = keyState === PRESSED ? "UP" : "STOP"
} else if(keyCode === DOWN){
player.go.dirY = keyState === PRESSED ? "DOWN" : "STOP"
} else if(keyCode === LEFT){
player.go.dirX = keyState === PRESSED ? "LEFT" : "STOP"
} else if(keyCode === RIGHT){
player.go.dirX = keyState === PRESSED ? "RIGHT" : "STOP"
}
});
});
The problem is certain keys don't fire the keyUp event when I release them so it creates a key blocked effect and the player keeps moving. It works for KeyW and KeyD but not KeyA and KeyS. I also tried to use the arrow keys instead, the ArrowUp and ArrowRight fires keyUp when I release them but not ArrowLeft and ArrowDown.
I read somewhere that it's an old bug and it's related to the OS and the browser. I use Ubuntu 16.10 and Chrome Version 68.0.3440.84 (64-bit). But I couldn't find any fix for it. Some people talked about a workaround using setTimout or setInterval without showing any demo. I don't know how to make it work but I can't let the player's moves depend on the OS and browser...
I hope someone will help me find a solution. Thanks !
[EDIT] I fixed the issue just by replacing "window.addEventListener(...)" by "document.addEventListener(...)".
Upvotes: 4
Views: 105
Reputation: 71
I fixed the issue just by replacing "window.addEventListener(...)" by "document.addEventListener(...)".
Upvotes: 1
Reputation: 125
Have you tried it without the triple equal "==="? That is saying that the 1 is the same type and equal to true. Either that or change the PRESSED constant to true instead of 1 and RELEASED constant to false instead of 0.
Upvotes: 0