Key.isDown( ) Method | Flash 5 |
check whether a specific key is currently depressed |
A number representing the keycode of the key to check. Can also be one of the Key constants (e.g., Key.UP, Key.BACKSPACE).
A Boolean indicating whether the key specified by keycode is currently depressed (true) or not (false).
The isDown( ) method tells us whether the key specified by keycode is currently being pressed, such as:
trace(isDown(65)); // Displays: true if the "A" key is depressed during the test
It offers immediate access to the state of the keyboard and is best used with systems that require constant key-based input or that detect the pressing of simultaneous keys.
The isDown( ) method offers three advantages over getCode( ) and getAscii( ); it can:
Detect the state of modifier keys such as Ctrl, Command, Shift, and Option, which do not trigger keyboard events on their own. (To determine whether the Caps Lock, Num Lock, and Scroll Lock keys are in their locked (down) state, use isToggled( ) instead.)
Detect the state of arbitrary keys, allowing programmers to check for the simultaneous pressing of multiple keys.
Detect whether a key is currently being pressed (getCode( ) and getAscii( ) tell you which key was last pressed, but it may have been subsequently released).
Unlike getCode( ) and getAscii( ), which always return the last key pressed (even if it has since been released), isDown( ) accepts a keycode argument specifying which keycode to test. By checking both Key.UP and Key.RIGHT in separate calls to isDown( ), for example, we can determine whether a spaceship in a game should be moved diagonally. Depending on the placement of the specific keys being tested, the maximum number of keys that can be detected simultaneously may be as low as three.
The isDown( ) method normally is used to create systems that undergo repeated updates with each passing frame. In the following code, we rotate and thrust a spaceship on any frame where the appropriate arrow keys are being pressed. Note that if you need to detect two keys simultaneously, you should use separate if statements. In this example, the state of the right arrow key is ignored if the left arrow key is depressed. Regardless, the state of the up arrow key is always checked in a separate if statement. A working version of this spaceship example is available at the online Code Depot:
// Code for a spaceship clip spaceship_mc.onEnterFrame = function () { if (Key.isDown(Key.LEFT)) { // Left arrow this._rotation -= 10; } else if (Key.isDown(Key.RIGHT)) { // Right arrow this._rotation += 10; } if (Key.isDown(Key.UP)) { // Up arrow this.thrust += 10; } }
Button keyPress, Key.getAscii( ), Key.getCode( ), Key.isToggled( ); Appendix B