KeyboardEvent

This example makes a listener on the stage and then makes "movingthing_mc" move according to the keyboard arrows that are pressed. Currently everything is set to move at the rate of 5 pixels per keypress, but this can be changed to a bigger number to make the movement faster.

http://dreamsyntax.org/patterns/swf/keyboardevent_01.swf

stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKeyToMove);

function pressKeyToMove(event:KeyboardEvent):void {	switch (event.keyCode){ case Keyboard.UP: trace("You pressed up"); movingthing_mc.y -= 5; break;

case Keyboard.DOWN: trace("You pressed down"); movingthing_mc.y += 5; break;

case Keyboard.LEFT: trace("You pressed left"); movingthing_mc.x -= 5; break;

case Keyboard.RIGHT: trace("You pressed right"); movingthing_mc.x += 5; break; } } 

keyDownHandler and keyUpHandler
When you create a program, you might do something like this. I like to give my functions clear and meaningful names that you can understand and easily identify later. You could actually call it anything you like, but don't blame me later if you can't recall why you named this function with your own name or what the function is supposed to do.

 stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler); stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);

private function keyDownHandler(evt:KeyboardEvent) {		if (evt.keyCode == 32) //spacebar is pressed {			firing = true; }	} private function keyDownHandler(evt:KeyboardEvent) {		if (evt.keyCode == 32) //spacebar is pressed {			firing = false; }	} 

Partial List of Some keyCodes
We often use the numbers to refer to the keyCodes instead of writing DOWN and UP as the numbers are more precise and you will know nothing can go wrong by referring to the numerical keyCode!


 * Backspace = 8
 * Tab = 9
 * Enter = 13
 * Shift = 16
 * Control = 17
 * CapsLock = 20
 * ESC = 27
 * Spacebar = 32
 * PageUp = 33
 * PageDown = 34
 * End = 35
 * Home = 36
 * LeftArrow = 37
 * UpArrow = 38
 * RightArrow = 39
 * DownArrow = 40
 * Insert = 45
 * Delete = 46
 * NumLock = 144
 * ScrollLock = 145
 * Pause/Break = 19