Handling keyboard events for a particular object : KeyboardEvent « Development « Flash / Flex / ActionScript






Handling keyboard events for a particular object

 
package {
  import flash.display.*;
  import flash.events.*;

  public class Main extends Sprite {
    public function Main(  ) {
      var rect1:Sprite = new Sprite(  );
      rect1.graphics.lineStyle(1);
      rect1.graphics.beginFill(0x0000FF);
      rect1.graphics.drawRect(0, 0, 75, 75);
      rect1.tabEnabled = true;

      var rect2:Sprite = new Sprite(  );
      rect2.graphics.lineStyle(1);
      rect2.graphics.beginFill(0x0000FF);
      rect2.graphics.drawRect(0, 0, 75, 75);
      rect2.x = 200;
      rect2.tabEnabled = true;

      addChild(rect1);
      addChild(rect2);

      rect1.addEventListener(KeyboardEvent.KEY_DOWN, rect1KeyDownListener);
      rect2.addEventListener(KeyboardEvent.KEY_DOWN, rect2KeyDownListener);
    }

    private function rect1KeyDownListener (e:KeyboardEvent):void {
      Sprite(e.target).x += 10;
    }

    private function rect2KeyDownListener (e:KeyboardEvent):void {
      Sprite(e.target).rotation += 10;
    }
  }
}

        








Related examples in the same category

1.KeyboardEvent Basics
2.Understanding keyCodes
3.Listen for the keyDown event and traces out the character code for that key.
4.Handling keyboard events globally
5.Retrieving a pressed key's key code through KeyboardEvent.KEY_DOWN event
6.Reference key code with Keyboard.ESCAPE
7.Multilocation keys
8.Up / Left Sensor
9.Determining the Character Associated with a Key
10.Converting user input to uppercase