问题
I'm new to ActionScript development and am using the FlashDevelop IDE. I've been playing around with some really simplistic things and have come across a problem I can't seem to solve.
My application compiles and runs, and a function that watches click events fires perfectly and I can see the event in the console when I pass it to trace(), yet the same code watching for KeyboardEvent fails to fire at all.
Here's my code:
package GameTesting
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
[Frame(factoryClass="GameTesting.Preloader")]
public class Main extends Sprite
{
public function Main():void
{
if (stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
addEventListener(MouseEvent.CLICK, onClickEvent);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownEvent);
}
private function onKeyDownEvent(e:KeyboardEvent):void
{
trace(e);
}
private function onClickEvent(e:MouseEvent):void
{
trace(e);
}
}
}
The MouseEvent trace() fires every time as expected, but KeyboardEvent never fires, no matter what key I press. Any ideas?
回答1:
You need to add the listeners to the stage:
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
stage.addEventListener(MouseEvent.CLICK, onClickEvent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownEvent);
}
回答2:
You may need to be sure the movieclip listening for the event has focus. If you have some sort of menu or start screen for your game that you click a button on to start, that movieclip can retain focus even if it has been removed from stage.
Here's a good article explaining this in further detail: Keyboard events on stage are not working...?
回答3:
If you are in the Flash IDE (for CS4 at least) you will also need to disable the keyboard shortcuts when you debug (Ctrl+Shift+Enter) or test (Ctrl+Enter) the fla.
In the movie window, select 'Control'->'Disable Keyboard Shortcuts'. This will stop the Flash IDE recieving the keyboard input, and allow the debug/test window to instead.
来源:https://stackoverflow.com/questions/4100402/actionscript-3-keyboardevent-not-firing