I am trying to create a simple javascript program that reads keydown events and translates them into motion on an HTML canvas. So far I have had quite a bit of success, I have had a strange problem with (as I believe) the priority of the shooter. It happens that if I hold the right arrow and I click on the left arrow, then the left arrow takes over. If I hold the left arrow and I press the right arrow, nothing changes (the block that I move continues to move to the left). I am switching the key reading order, but have not succeeded.
My code for reading bulletins and keys:
//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; });
Then it is 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 someone see, or does anyone already know why the left key will take precedence over the right one?
SOLVE:
The 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; } };
source share