Detecting key presses in AS3
February 25th, 2008 by
Adrian Parr
![]()
In ActionScript 3 you can detect key presses on the keyboard using the Stage class. I discovered that the Stage object is not globally accessible. You need to access it through the stage property of a DisplayObject instance. So from within a Class you can check which keys are being pressed using the following code.
package {
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
public class KeyboardTest extends MovieClip {
private var base:MovieClip;
public function KeyboardTest($base:MovieClip):void {
trace("KeyboardTest constructor is being run");
base=$base;
base.stage.addEventListener(KeyboardEvent.KEY_DOWN,keyboardListener);
}
private function keyboardListener(event:KeyboardEvent):void {
trace("event.keyCode: " + event.keyCode);
}
}
}
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
public class KeyboardTest extends MovieClip {
private var base:MovieClip;
public function KeyboardTest($base:MovieClip):void {
trace("KeyboardTest constructor is being run");
base=$base;
base.stage.addEventListener(KeyboardEvent.KEY_DOWN,keyboardListener);
}
private function keyboardListener(event:KeyboardEvent):void {
trace("event.keyCode: " + event.keyCode);
}
}
}
Posted in ActionScript 3.0, Sample Code |
No Comments »