I'm trying to recreate a Pong game by Atari and am currently stuck at multiple key handlers.
The problem i have with a current solution is that browser does not seem to handle multiple key input and that's why I can't move both paddleys smoothly enough.
The way i handle key input looks like this atm:
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 40) {
DownArrowPressed = true;
console.log('down pressed')
}
else if(e.keyCode == 38) {
UpArrowPressed = true;
console.log('up pressed')
}
else if(e.keyCode == 68) {
Dpressed = true;
console.log('d pressed')
}
else if(e.keyCode == 67) {
Cpressed = true;
console.log('c pressed')
}
}
function keyUpHandler(e) {
if(e.keyCode == 40) {
DownArrowPressed = false;
}
else if(e.keyCode == 38) {
UpArrowPressed = false;
}
else if(e.keyCode == 68) {
Dpressed = false;
}
else if(e.keyCode == 67) {
Cpressed = false;
}
}
P.S. I've been browsing stackoverflow and found this thread: javascript multiple keys pressed at once
Update: the code using above mentioned thread:
> document.addEventListener("Down", onkeydown, false);
document.addEventListener("up", onkeyup, false);
var map = []; // Or you could call it "key"
onkeydown = onkeyup = function(e){
e = e || event; // to deal with IE
map[e.keyCode] = e.type == 'keydown';
// D + up arrow
if (map[68] && map["38"]) {
Dpressed = true;
UpArrowPressed = true;
}
// D + down arrow
else if (map[68] && map["40"]) {
Dpressed = true;
DownArrowPressed = true;
}
// C + up arrow
else if (map[67] && map[38]) {
Cpressed = true;
UpArrowPressed = true;
}
// C + down arrow
else if (map[67] && map[40]) {
Cpressed = true;
DownArrowPressed = true;
}
// Down arrow
else if(map[40]) {
DownArrowPressed = true;
}
// Up arrow
else if(map[38]) {
UpArrowPressed = true;
}
// D
else if(map[68]) {
Dpressed = true;
}
// C
else if( map[67]) {
Cpressed = true;
}
}
With this code, the paddles don't move smoothly and stuck at the bottom of a canvas. I feel there are mistakes in my implementation, but i can't see them -_-