This tutorial will explain how to enable keyboard commands in Flash Actionscript 3 CS3.
Firstly we need to import the Keyboard class in flash this can be done by:
import flash.events.KeyboardEvent;
After we have imported the keyboardEvent package, it is necessary to add an event listener to the stage, otherwise Flash will not know that we are pressing a key, and will not know what to do with it.
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);
We need to create a function for our KeyPressed event listener but inside our function we create a switch statement to determine what the function should do when a certain key is pressed. Inside our parameters we have the argument evt.KeyCode this gets the key code for the key that was pressed to trigger the event.
function KeyPressed(evt:KeyboardEvent):void {switch (evt.keyCode){ case Keyboard.UP :break;case Keyboard.DOWN :break;case Keyboard.LEFT :break;case Keyboard.RIGHT :break; } }
After you have specified what keys you would like to use, you can link them for example to move something. For example, if you want a square to move in the x direction when the “up” arrow is pressed on the keyboard you would add square.y += 5;
so the code above would be modified to look like this:
case Keyboard.UP :square.y += 5;break;