Multiple Keys

Actionscript:
  1. var key:Object = new Object();
  2. stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
  3. stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
  4. function onKeyPressed(evt:KeyboardEvent):void {
  5.     key[evt.keyCode] = true;
  6.     key.keyCode = evt.keyCode;
  7. }
  8. function onKeyReleased(evt:KeyboardEvent):void {
  9.     key[evt.keyCode] = false
  10. }
  11.  
  12. // example
  13.  
  14. addEventListener(Event.ENTER_FRAME, onLoop);
  15. function onLoop(evt:Event):void {
  16.    
  17.     //trace(key.keyCode);
  18.      
  19.     if (key[Keyboard.LEFT]){
  20.         trace("left");
  21.     }
  22.    
  23.     if (key[Keyboard.RIGHT]){
  24.         trace("right");
  25.     }
  26.    
  27.     // keys #1, #2 and #3 are down
  28.     if (key[49] && key[50] && key[51]){
  29.         trace("one two thee");
  30.     }
  31.    
  32.     // keys #6, #7, #8 and #9 keys are down
  33.     if (key[54] && key[55] && key[56] && key[57]){
  34.         trace("six seven eight nine");
  35.     }
  36. }

The first 10 lines of code make up this snippet. This is an easy way to keep track of multiple key presses. For games, this is the only key technique I use ... wrapped up in a Singleton.

This entry was posted in associative arrays, keys and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Posted October 15, 2009 at 2:15 am | Permalink

    hi,
    my doubt is that when multiple keys have been pressed like on line 28 and 33,
    how do i make my clip move diagonally…

  2. Posted October 15, 2009 at 2:16 am | Permalink

    say when i press the left and up key my clip should move diagonally left up….

  3. Posted October 15, 2009 at 7:56 am | Permalink

    vibil… well…. this snippet works nicely for that… try this code:

    var character:Shape = Shape(addChild(new Shape()));
    with(character.graphics) beginFill(0×000000), drawCircle(0,0,10);
    character.x = character.y = 100;

    var key:Object = new Object();
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
    stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
    function onKeyPressed(evt:KeyboardEvent):void {
    key[evt.keyCode] = true;
    key.keyCode = evt.keyCode;
    }
    function onKeyReleased(evt:KeyboardEvent):void {
    key[evt.keyCode] = false
    }
    // example
    addEventListener(Event.ENTER_FRAME, onLoop);
    function onLoop(evt:Event):void {
    //trace(key.keyCode);
    if (key[Keyboard.LEFT]){
    character.x -= 4;
    }
    if (key[Keyboard.RIGHT]){
    character.x += 4;
    }
    if (key[Keyboard.UP]){
    character.y -= 4;
    }
    if (key[Keyboard.DOWN]){
    character.y += 4;
    }
    }

  4. vibil
    Posted December 8, 2009 at 6:49 am | Permalink

    Hey thanx very much.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*