I'm trying to create a simple javascript program that reads keydown events and translates them into movement on an HTML canvas. I've had a fairly large degree of success so far, I'm having a strange issue with (what I assume is) arrow key precedence. What happens is that, if I'm holding the right arrow, and I press down the left arrow, then the left arrow takes over. If I'm holding down the left arrow, and I press down the right arrow, nothing changes (the block I'm moving continues to move to the left). I've switching the order that keydowns are read, but have had no success.
My code for reading keydowns and keyups is this:
//Listener for when keys are pressed
window.addEventListener('keydown', function (event) {
keyCodes[event.keyCode] = true;
});
//Listener for keys being released
document.addEventListener('keyup', function (event) {
keyCodes[event.keyCode] = false;
});
It is then interpreted here
//movement function
function move () {
if (keyCodes[right]) {
velX = 12.0;
}
if (keyCodes[left]) {
velX = -12.0;
}
};
function update() {
if (keyCodes[right] || keyCodes[left])
move();
posX += velX;
if (!keyCodes[right] && velX > 0)
velX -= gravity;
if (!keyCodes[left] && velX < 0)
velX += gravity;
};
Can anyone see, or does anyone already know, why the left key would be taking priority over the right one?
SOLVED:
Corrected move function is as follows:
function move () {
if (keyCodes[left] && velX > -12.0) {
velX -= 2.0;
}
if (keyCodes[right] && velX < 12.0) {
velX += 2.0;
}
};
ifstatements inmove()andupdate()(testing thekeyCodes[left]values first). See if that changes the behavior. If so, the problem is in your logic for dealing with the events. If not, it's probably some sort of ambiguity in JS's handling of multi-presses (and possibly browser specific). - Ted Hopp