Tag Archives: keys

KeyCode Variables

Actionscript:
  1. // create constants for all letter and number keys:
  2. var alphabet:Array = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
  3. var nums:Array = ["ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"];
  4.  
  5. var key:Object = new Object();
  6. for (var i:int  = 0; i<alphabet.length; i++)
  7.      key[alphabet[i]] = 65 + i;
  8.      
  9. for (i = 0; i<nums.length; i++){
  10.      var code:int = 48 + i;
  11.      key[nums[i]]= code;
  12.      key[i] = code;
  13. }
  14.      
  15.  
  16. // test them out
  17. stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
  18. function onKeyPressed(evt:KeyboardEvent):void {
  19.     if (evt.keyCode == key.A){
  20.         trace("the a was pressed");
  21.     }
  22.     if (evt.keyCode == key.B){
  23.         trace("the b was pressed");
  24.     }
  25.     if (evt.keyCode == key.NINE){
  26.         trace("the 9 key was pressed");
  27.     }
  28.     if (evt.keyCode == key["0"]){
  29.         trace("the 0 key was pressed");
  30.     }
  31. }

This is an easy way to store values for alphanumeric keys in variables that make sense... instead of having to do things like this:

Actionscript:
  1. // hit the zero key
  2. if (evt.keyCode == 48){
  3.    trace("the zero key was hit");
  4. }

Posted in Object, keys | Also tagged , | Leave a comment