The Key class is a useful tool for capturing key events from the user (that is, user interaction with the keyboard). You can employ the Key class for tasks such as these:
Determining whether a specific key is currently pressed
Determining the last key pressed
Obtaining the key code value of the last key pressed
Adding a Listener that watches for a key event
Determining whether a certain key (such as Caps Lock) is toggled on or off
The Key class is a top-level class, which means you cannot create a new instance of it. The most common use of the Key class is to determine whether a specific key is pressed. You would use this syntax to determine whether a key is being pressed:
Key.isDown(Key.TAB);
The script uses the isDown() method of the Key class to determine whether the Tab key is currently pressed down. It returns a result of either true or false. The parameter of the isDown() method can reference either a specific key in the Key class or the key code of a specific key. Every key on your keyboard has a special number associated with it, called a key code. For example, the Tab key can be referenced using Key.TAB, or by the number 9, which is its ASCII equivalent. This script is the essentially the same as the preceding one:
Key.isDown(9);
In the next simple exercise, you'll move a hot air balloon around the screen using your keyboard and the Key class.
Open balloon1.fla in the Lesson04/Assets directory.
This movie contains three layers: Background, Balloon, and Actions. On the Balloon layer, you'll see a movie clip instance of a hot air balloon with an instance name of balloon_mc. The Background layer simply displays an image. In this exercise, you'll place actions on the first frame of the Actions layer.With the Actions panel open, select Frame 1 in the Actions layer and add this script:
var speed:Number = 3;
With Frame 1 still selected, add this script at the end of the current script:
_root.onEnterFrame = function() { if (Key.isDown(Key.RIGHT)) { balloon_mc._x += speed; } else if (Key.isDown(Key.LEFT)) { balloon_mc._x -= speed; } };
Add this ActionScript to the enterFrame clip event:
if (Key.isDown(Key.UP)) { balloon_mc._y -= speed; } else if (Key.isDown(Key.DOWN)) { balloon_mc._y += speed; }
Choose Control > Test Movie. Use the Left, Right, Up, and Down Arrow keys to control the movement of the hot air balloon.
The conditional statements you wrote are performed in each frame of the onEnterFrame clip event. If one of the keys is detected to be in the down state, the balloon will be moved accordingly.Close the test movie and save your work as balloon2.fla.
Now you know how to capture a keypress and make something happen as a result. This script has many applications, including paging through a slide show or making a game.