In Javascript, how do I tell if a user is pressing two keys at the same time?
For example, I have drawn a circle in the middle of the screen. I want to move it up while
Javascript has onkeydown, and onkeyup events. You can simple fiddle a bit onkeydown for left arrow, and fiddle another bit for the up arrow. On keyup, fiddle the respective bit back.
var leftPressed,
upPressed,
rightPressed,
downPressed;
var milli = 100;
window.addEventListener('onkeydown', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = true;
case 38: //up
upPressed = true;
case 39: //right
rightPressed = true;
case 40: //down
downPressed = true;
default:
break;
}
});
window.addEventListener('onkeyup', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = false;
case 38: //up
upPressed = false;
case 39: //right
rightPressed = false;
case 40: //down
downPressed = false;
default:
break;
}
});
function moveCircle() {
if(leftPressed && !rightPressed) {
// move left
}
if(rightPressed && !leftPressed) {
// move right
}
if(upPressed && !downPressed) {
// move up
}
if(downPressed && !upPressed) {
// move down
}
}
setInterval(moveCircle, milli);