PDA

View Full Version : key listener trouble



bottleboy
June 11th, 2007, 10:45 AM
I'm having trouble with my key listener. This code works fine when I run Test Movie, but when I just run the exported swf, the keys seem to get stuck. It doesn't recognize when I release a key. What is the difference between Test Movie and just running the exported swf file?

I did this in FlashMX 7.0 and I'm running it on an Intel Mac.


// Listener to those keys
keyListener = new Object();

// Key pressed down
keyListener.onKeyDown = function() {

switch (Key.getCode()) {
case Key.LEFT:
leftKey = true;
break;
case Key.RIGHT:
rightKey = true;
break;
case Key.DOWN:
downKey = true;
break;
case Key.UP:

upKey = true;
break;
case Key.SPACE:
fireKey = true;

break;
}
};

// Key released
keyListener.onKeyUp = function() {
switch (Key.getCode()) {
case Key.LEFT:
leftKey = false;
break;
case Key.RIGHT:
rightKey = false;
break;
case Key.DOWN:
downKey = false;
break;
case Key.UP:
upKey = false;

break;
case Key.SPACE:
fireKey = false;

break;
}
};

Key.addListener(keyListener);

pingnak
June 11th, 2007, 01:24 PM
In AS3, where you HAVE TO do that, the key event handlers have to be attached to the 'stage' and nowhere else (or it misses them by the bucket-load) and you also need to hook Event.ACTIVATE and Event.DEACTIVATE, else it won't know when the app loses focus to clear your cached 'down' state.

But in AS2, you don't have Event.ACTIVATE and Event.DEACTIVATE, so no matter what you do with that notify code, when your applet loses focus and regains it, whatever keys were down when the focus changed will be 'stuck'.

You're far better off in AS2 code using Key.isDown(code) wherever it is that you're polling those booleans.

There's a neat-o security hole with Flash 8 and earlier: Since Key.isDown(code) ALWAYS works, you could write a key logger with it to capture passwords and whatnot. As of Flash 9, that's fixed, but you ought to be careful because no matter what your Flash IDE will run the 'older' Flash with the security hole, so beware of what you run with it.

bottleboy
June 12th, 2007, 08:48 PM
yup, Key.isDown worked just fine. thanks!