Key.onKeyUp( ) Listener Event | Flash 6 |
occurs when a key is released |
The onKeyUp( ) event is triggered when a key is depressed and then released. It is sometimes used in game programming to turn off something that was turned on by an earlier onKeyDown( ) event�the classic example being a spaceship's thrust. The onKeyUp( ) event can be handled by an event listener, as specified by listener, that has been added using addListener( ). The onKeyUp( ) event can also allow a key to modify an application's behavior temporarily. For example, in the Flash authoring tool, holding down the spacebar temporarily switches to the Hand tool, and releasing the spacebar restores the previous tool. A similar approach can be used to show and hide things in an application, such as temporary menus.
To respond to an onKeyUp( ) event, we must first assign a callback function to the onKeyUp property of some object, such as listener, and then add listener as a listener using Key.addListener( ), as follows:
// Make a generic object keyListener = new Object(); // Assign a function to the object's onKeyUp property keyListener.onKeyUp = function () { trace("A key was released!"); } // Register the listener with the Key object Key.addListener(keyListener);
Any number of listener objects can respond to the onKeyUp( ) event. As with onKeyDown( ), in order to obtain useful information from an onKeyUp( ) event, we normally use it with other methods of the Key object:
keyListener.onKeyUp = function () { trace("The last key released was " + Key.getAscii()); } }
The onKeyDown( ) and onKeyUp( ) events are triggered precisely once for each keypress and key release. When using onKeyUp( ) and onKeyDown( ), you need not concern yourself with whether the key is still being pressed at any given instant. Using these events allows you to detect keypresses accurately even if the user releases the key between frames, and it also prevents you from checking the same key twice if it was pressed only once. In any case, you will ordinarily use the Key.getCode( ) and Key.getAscii( ) methods to check for the last key pressed within an onKeyDown( ) or onKeyUp( ) listener.
The onKeyUp( ) event executes immediately when a key is released, independent of the code on a movie's timeline(s). However, visual changes to the movie made by the listener are not rendered until the next frame refresh, which is determined by the frame rate of the movie. Unfortunately, in Flash 6, updateAfterEvent( ) cannot be used to force a screen refresh from onKeyUp( ); updateAfterEvent( ) has an effect only when invoked either from a movie clip mouse or key event, or a setInterval( ) callback.
To emulate onKeyUp( ) in Flash 5, use the MovieClip class's on(keyUp) clip event attached to a movie clip at authoring time. For example:
onClipEvent (keyUp) { trace("Some key was released"); }
Key.addListener( ), Key.onKeyDown( ), MovieClip.onKeyUp( )