What is the correct way to detect held keys in a flash game? For example, I want to know that the right arrow is held to move the player.
Naive code:
function handleKeyDown(event:KeyboardEvent) {
held[event.keyCode] = true;
}
function handleKeyUp(event:KeyboardEvent) {
held[event.keyCode] = false;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
The naive code has problems on some computers. The KEY_DOWN event is alternating with KEY_UP many times for a held key there. That makes the key appear to be released in some frames.
An example of the seen events:
[Just holding a single key.]
KEY_DOWN,KEY_UP,KEY_DOWN,KEY_UP,KEY_DOWN,KEY_UP,...