aidanjacobson
aidanjacobson

Reputation: 2401

Multiple arrow keys on keypress

I would like to make a game in html and javascript that uses the arrow keys to move. I have already tried

window.onkeydown = function(e) {
    if (e.which == 37) {
        doleftarrowkeystuff();
    }
    if (e.which == 39) {
        dorightarrowkeystuff();
    }
};

but that stops one key when the other is pressed.

Any help would be appreciated.

Upvotes: 0

Views: 1449

Answers (2)

aidanjacobson
aidanjacobson

Reputation: 2401

Actually, I figured it out. I can just look for the onkeyup event. For example, I can use

var right = 0;
var left = 0;
window.onkeydown = function(e) {
    if (e.which == 37) {
        left = 1;
    }
    if (e.which == 39) {
        right = 1;
    }
};
window.onkeyup = function(e) {
    if (e.which == 37) {
        left == 0;
    }
    if (e.which == 39) {
        right == 0;
    }
};

(please don't tell me if I mix left and right up, I'll figure it out)

Upvotes: 1

ariel_556
ariel_556

Reputation: 378

exist onkeyup as well, you can check every keypressdown and store it, but when the onkeyup is triggered check if it is the same key in order to remove from store.

Upvotes: 1

Related Questions