The web site for Flash ActionScript 3.0 game developers

 
         
   

KEY_UP, KEY_DOWN Woes

Ok, here is my problem. Using the system you illustrated in your book for keyboard movement, I have a problem which I just cannot seem to figure out. Here is the code for movement, which you'll have seen a million times already :P

public var leftArrow,rightArrow,downArrow,upArrow:Boolean = false;

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);

public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 37 || event.keyCode == 65) {
leftArrow = true;
} else if (event.keyCode == 39 || event.keyCode == 68) {
rightArrow = true;
} else if (event.keyCode == 38 || event.keyCode == 87) {
upArrow = true;
} else if (event.keyCode == 40 || event.keyCode == 83) {
downArrow = true;
}
}

public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37 || event.keyCode == 65) {
leftArrow = false;
} else if (event.keyCode == 39 || event.keyCode == 68) {
rightArrow = false;
} else if (event.keyCode == 38 || event.keyCode == 87) {
upArrow = false;
} else if (event.keyCode == 40 || event.keyCode == 83) {
downArrow = false;
}
}

Ok, so that's the code I use, everything else, acts on if the boolean variables are set to true or false, like in your example. The only modification to the code is the extra keyCode which enables the user to use UP,DOWN,LEFT,RIGHT And or, WASD too. However, that is not final, and the finished product will likely have the ability to change these keys... Anyway.

My problem is this:

The system is awesome, unless.. If WHILE HOLDING a key, the user right-clicks, or sometimes it happens on it's own, perhaps if the keyboard thinks you're pressing too many keys. ( It would usually happen too if the window lost focus, but I have a function in place to automatically pause the game and set all the movement variables to false in this case, so it does not matter. ) The game doesn't register that the user has released a key, and because of this, the variable remains true, while the user ISNT holding the key down. The only way to counter this is to have the window lose focus and it resets all of the variables to false, Or to have the user press the button corresponding to the True variable, and then release it.

Is there a way I can prevent this from happening? I would really appreciate your assistance.

Thanks for taking to time to read,
Regards

Pete



Copyright Gary Rosenzweig