I am in the process of designing a simple game where the player flies a ship around using the arrow keys. I currently use a series of switch statements to execute certain actions dependant upon which key(s) is(are) pressed. Here is the code I use:
Code:
window.addEventListener('keydown', function (event) {
switch (event.keyCode) {
case arrowLeft: //left
player.moveLeft = true;
player.vr = -1;
break;
case arrowRight: //right
player.moveRight = true;
player.vr = 1;
break;
case arrowUp: //up
player.moveUp = true;
player.thrust = thrust;
break;
case arrowLeft && arrowUp:
player.moveLeft = true;
player.vr = -1;
player.moveUp = true;
player.thrust = thrust;
break;
case arrowRight && arrowUp:
player.moveRight = true;
player.vr = 1;
player.moveUp = true;
player.thrust = thrust;
break;
case arrowRight && arrowLeft && arrowUp:
player.moveUp = true;
player.thrust = thrust;
break;
}
}, false);
// Keyup input listeners
window.addEventListener('keyup', function (event) {
switch (event.keyCode) {
case arrowLeft: //left
player.vr = 0;
player.moveLeft = false;
break;
case arrowRight: //right
player.vr = 0;
player.moveRight = false;
break;
case arrowUp: //up
player.thrust = 0;
player.moveUp = false;
break;
}
}, false);
The problem I am having is that the key presses don't always seem to register. For example, the player cannot always smoothly switch from a right turn quickly to a left turn. Sometimes he can, but oftentimes it seems like the key press is not always registered and the player must mash the key a second time to finally get it to register. Is there a more reliable method for listening for and registering key presses vs. using a switch statement or a bunch of if statements (which gave me the same result)?