I'm working on an RPG in Javascript and am setting up controls for the main player, but I am having some issues with the keyEvent handling. This code controls player movement and animation. Where things go wrong, I believe, is that if the game registers a keydown while there is already another keydown, and then that first key goes up, the sprite pauses (the isMoving property basically stops movement and animation when it is false).
// For example:
// I hold W. Sprite begins moving up.
// While holding W, I begin to hold D. Sprite begins moving right.
// I release W. Sprite should keep going right, but pauses momentarily when the
// keyup is registered
var move = function(e) {
xavier.isMoving = true;
switch(e.keyCode)
{
case 87: xavier.direction = 'up'; break; //W
case 65: xavier.direction = 'left'; break; //A
case 68: xavier.direction = 'right'; break; //D
case 83: xavier.direction = 'down'; break; //S
};
};
var wait = function(e) {
xavier.isMoving = false;
};
window.addEventListener("keydown", move, false);
window.addEventListener("keyup", wait, false);
Is there a better way to set up controls so that my game can handle multiple keys simultaneously?
Also, the sprite moves when mac command key is pushed. Not sure why.