Tuesday, September 13, 2011

ActionScript 3 Keyboard Events


In order to create a fully interactive flash movie, you need to know something about keyboard events. This tutorial is all about catching ActionScript 3.0 keyboard events and responding to them. So let’s get started!
Click on the stage and start pressing some buttons. See how the values change. Now let’s look the code behind this movie.

Moving to ActionScript 3.0

Here is the code behind the ActionScript keyboard event movie.
 
stage.addEventListener (KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener (KeyboardEvent.KEY_UP, keyUpHandler);
 
function keyDownHandler (e:KeyboardEvent):void {
 
 keyDownText.text = 
 "Key code: " + e.keyCode + "\n" +
 "Ctrl status: " + e.ctrlKey + "\n" +
 "Key location: " + e.keyLocation + "\n" +
 "Shift key: " + e.shiftKey + "\n";
}
 
function keyUpHandler (e:KeyboardEvent):void {
 
 keyUpText.text = "Key code: " + e.keyCode;
}
As you can see, the code is really simple. The “keyDownText” and “keyUpText” are just dynamic text fields, where we put the keyboard event text. Here are the explanations for the keyboard event properties.
keyCode: Every keyboard button has a numerical key code value. You don’t need to remember them of course. For example, use this movie to find the key’s corresponding value.
ctrlKey: Tells whether the control key is pressed or not. There is also a same kind of property for the alt button called “altKey”.
keyLocation: This property indicates the location of the key on the keyboard. For example press the right shift button and see the location value for it. Then press the left shift button. As you can see, the location value changes. This is how you can differentiate same keys in the keyboard. This comes especially useful if you want to differentiate the keys between a numeric keypad and a standard keyboard.
shiftKey: Tells whether the shift key is pressed or not.

No comments:

Post a Comment