AS3 Implementing Keyboard Controls

Today we will cover the topic on having a keyboard controls in AS3. This is an important element in game and interactive programming involving keyboard as input.

Like usual, below is a sample demo of my flash embedded. Try using arrow keys and spacebar. Watch the blue box move according to your controls. If the screen is too small, try click on the flash below to start.

Below are the source code and sample on how keyboard listeners are used in AS3.

Main.as
package 
{
	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
 
	/********************************************************************
	* Description : This is the main document Class file.
	* @author Alex T.
	 ********************************************************************/
	public class  Main extends MovieClip
	{
		public var mcCursor:MovieClip;
		public var MCCURSOR_X:int = 150;
		public var MCCURSOR_Y:int = 150;
 
		public function Main( ) {
			resetCursorPosition();
			// Attaching stage keyListeners to listen to keyboard input 
			stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown );
		}
 
		private function handleKeyDown( event:KeyboardEvent ):void {
			// This is where we handle what to do when there's an input
                        // event.keyCode returns a keyCode of the particular keyboard key.
			// trace( "KeyCode received : " + event.keyCode ) ;
			switch (event.keyCode) {
				case 32:
					      // Spacebar is pressed. Enables recentering.
					      resetCursorPosition();
				break;
 
				case 37:
					      // key left
                                              mcCursor.x = mcCursor.x - 2;
				break;
 
				case 38:
					      // key up   	
                                              mcCursor.y = mcCursor.y - 2;
				break;
 
				case 39:
                                              // key right						
                                              mcCursor.x = mcCursor.x + 2;
				break;
 
				case 40:
					      // key down						
                                              mcCursor.y = mcCursor.y + 2;
				break;
			}
		}
 
		private function resetCursorPosition():void {
			mcCursor.x = MCCURSOR_X;
			mcCursor.y = MCCURSOR_Y;
		}
	}
}

Today’s source code tutorial downloadable below.

Download Here