views:

232

answers:

1

Okay, I've tried about 8 different ways to get a key event into my code, and none of them seem to work. Can someone please tell me how I can move this ball when I press shift? Thank you in advance

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
  styleName = "plain"
    xmlns="cyanprime.*" 
    layout="absolute"
    width="600"
    height="400"
    frameRate="100"
    creationComplete="initApp()">

    <mx:Script>
        <![CDATA[
            public function initApp():void
            {

       Mouse.hide();
                canvas.init();
       canvas.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
            }

      private function keyDown(event:KeyboardEvent):void
      {
       canvas.KeyDownHandler(event);
      }
     ]]>
    </mx:Script>

  <MyGameCanvas id="canvas" width="100%" height="100%" themeColor="#ff000000" />
</mx:Application>

...

package cyanprime{

    import mx.core.UIComponent;
    import mx.controls.Image;
    import flash.events.*;
    import flash.utils.*;
    import flash.display.*;
    import flash.ui.Keyboard;

    public class MyGameCanvas extends UIComponent{
     [Embed(source="player.gif")]
        private var playerImage:Class;

     private var player:DisplayObject = new playerImage();
     private var player_x:Number;
     private var player_y:Number;
     private var ticker:Timer;



     public function init():void{
            // set up player
            addChild(player);

      ticker = new Timer(10); 
            ticker.addEventListener(TimerEvent.TIMER, onTick);
            ticker.start();

     }

     public function KeyDownHandler(event:KeyboardEvent):void{
      if(event.keyCode == Keyboard.SHIFT)
      player_x += 50;
     }

     public function onTick(evt:TimerEvent):void {
     }  
    }
}
+2  A: 

you need to add the listener to the stage, and ad it after the applicationComplete event has occured (or in its handler)

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
 <mx:Script>
    <![CDATA[

    public function init():void
    {
     trace('Initialization');
     stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown); 
    }

    private function keyDown(event:KeyboardEvent):void
    {
     trace(event.charCode);
    }  
    ]]>
 </mx:Script>
</mx:Application>

ref

Joel Hooks