Game Development Reference
In-Depth Information
Keyboard events
Similar to handling other events such as mouse, timers, and others, keyboard key
handling is no different. Note that in most cases you don't need to handle it. For
example, in case of text field, text area, scroll bars, and more, you don't need to
handle the key strokes explicitly, as Flash does that for you.
However, for key handling to move your character on the screen, pick stuff up in
the game, or fire a weapon, you do need to handle it on your own.
The following is a simple example on handling keys on a sprite:
package {
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Keyboard extends Sprite
{
public function Keyboard()
{
// Set up the listener for the key board events
stage.addEventListener(KeyboardEvent.KEY_DOWN,
onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
// The callback fired when the key is pressed down
private function onKeyDown(e:KeyboardEvent):void {
trace("Event Key Down. Key Code: " + e.keyCode +
" Char Code: " + e.charCode);
}
// The callback fired when the key is let go
private function onKeyUp(e:KeyboardEvent):void {
trace("Event Key Up. Key Code: " + e.keyCode +
" Char Code: " + e.charCode);
}
}
}
When you try the previous example, you will see that the console prints the trace
logs every time a key is pressed down and every time the key is let go.
To help determine what key is pressed, you may examine the property of the event
that is passed into the callback. There are two codes that get passed in— keyCode
and charCode .
 
Search WWH ::




Custom Search