Actionscript Basics – Keyboard Input

keys

There are two main ways of having interactivity via a keyboard in flash. The first is to have the user type into a text box like we did in this tutorial where we set up a very unintelligent conversation bot. The second form of keyboard interactivity is to use an event listener to trigger an event when each key is pressed. The event listener for reading keyboard input looks like this:

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);

This adds a listener to the stage that will call the function “onKey” whenever a key is pressed down.

function onKey(myEvent:KeyboardEvent):void{
 
   trace(myEvent.keyCode);
 
}

Every key on the keyboard has a keycode (basically a numeric identifier).  Our function “onKey” receives a variable named “myEvent” from the listener which contains this keycode. In the function above we are outputing the keycode of the button pressed using the trace command.

Practical Example:

In this example we will use the arrow keys on the keyboard to control the position of a movie clip on the stage. This reminds me of the atari game Frogger.  Click on the movie clip to active the keyboard input.

The Flash plugin is required to view this object.

In the code for this example you will see it also makes use of the switch statement for efficiently checking which key was pressed.

Download .FLA source file

For a more sophisticated keyboard control, check out Emanuele Feronato‘s tutorial.

This entry was posted in Actionscript, Basic, Tutorials and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*