Will Pierce
Will Pierce

Reputation: 107

Mapping keyCodes together

const controls = {
    87: false, // W
    83: false, // S
    68: false, // D
    65: false, // A
    38: false, // Arrow up
    40: false, // Arrow down
    39: false, // Arrow right
    37: false, // Arrow left
};

document.body.addEventListener('keyup', keyUp, false);
document.body.addEventListener('keydown', keyDown, false);

function keyUp(event) {
    controls[event.keyCode] = false;
}

function keyDown(event) {
    controls[event.keyCode] = true;
}

I have added the ability to use both arrow keys and WASD keys to control player movement in my game. Currently, I'm checking for W and Arrow Up, S and Arrow Down (and so on) at the same time in my game logic.

if (controls[87] || controls[38]) { }

if (controls[83] || controls[40]) { }

if (controls[68] || controls[39]) { }

if (controls[65] || controls[37]) { }

Is there a way to map the Arrow Keys to the WASD keys instead of redundantly checking for two at the same time?

Example: From this...

if (controls[87] || controls[38]) { }

...to this:

if (controls[87]) { }

Upvotes: 0

Views: 55

Answers (1)

JSowa
JSowa

Reputation: 10662

No, there is no one keycode for both W and UP arrow and so on.

You can create function like this:

function isKeyCodeUp(keyCode) {
    return keyCode === controls[87] || keyCode === controls[38];
}

And then just call it:

if (isKeyCodeUp(event.keyCode)) {

Another decorator for the problem:

if ([87,38].includes(event.keyCode)) {

OR

const KEYCODE_UP = [87,38];
if (KEYCODE_UP.includes(event.keyCode)) {

Upvotes: 1

Related Questions