Let me explain my situation… I’m making a 2D platformer game, where you can go around and shoot stuff. Going around uses W, A & D keys, and shooting is done with the mouse. When I do all of the actions separately, everything works, but when I click the mouse button, and press a key in the same time, my code starts acting as if the key was still pushed down. This happens only sometimes.
I register all the keyboard events like this:
<body onload="init()" onkeydown="press(event);" onkeyup="release(event);">
Here’s the script that handles that:
var KEY = {W: 87, A: 65, S:83, D: 68, E: 69};
var input = {
right: false,
up: false,
left: false,
down: false,
e: false
};
function press(evt) {
var code = evt.keyCode;
switch(code)
{
case KEY.W: input.up = true; break;
case KEY.A: input.left = true; break;
case KEY.S: input.down = true; break;
case KEY.D: input.right = true; break;
case KEY.E: input.e = true; break;
}
}
function release(evt)
{
var code = evt.keyCode;
input.code = code;
switch(code)
{
case KEY.W: input.up = false; break;
case KEY.A: input.left = false; break;
case KEY.S: input.down = false; break;
case KEY.D: input.right = false; break;
case KEY.E: input.e = false; break;
}
}
Even when I don’t register mouse events, this happens. Can someone explain why? And how do I fix this?
EDITED
It seems, that the jerky behavior is not occasionally. If you press and keep
leftand then pressupand releaseleft, the movement continues. But, if you releaseupafter a while, movement will stop. Ie. you can make continuous circular moves, but you can’t get back to the original direction. This perhaps dues to the eventhandling process, using stack-type saving for event calls and their return-points.Below is an example code, which does the trick. It uses arrow-keys to move the spot. The code is in global space for clarity, and done for IE only, but you just edit it as you wish.