开发者

keyboard input with actionscript

I'm writing in pure actionscript in notepad with flex as a compiler. Here's the code I have

package 
{
 import flash.display.*;  
 import mx.core.*;  
    import flash.events.*;   
 import mx.collections.*;
 import flash.geom.*;  
 import mx.controls.*;
 import flash.text.*;  
 import mx.events.*;       
 import mx.styles.*;      
 import mx.containers.*;

 public class MAIN extends Sprite
 {
  public var APPLICATION:Application = Application(Application.application);
  public var FRAME:int = 0;
  public function MAIN()
  {
   addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
   STEP();
  }
  public function STEP():void
  {
   FRAME ++;
   STEP();
  }
  public function keyDownHandler(event:KeyboardEvent):void 
  {
   var keyDownText:TextField = new TextField();
   keyDownText.text = "Key code: " + event.keyCode;
   this.addChild(keyDownText);
  }
 }
}

What I want is for whatever ke开发者_开发知识库y I happen to press to be drawn on the screen (though actually I think it would only be the ascii number it corresponds to but that doesn't matter). Right now though everything's just blank. Another thing is because I'm not using any mxml I don't know if i've established the game loop correctly so let me know if that needs to be fixed.


Try

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);

instead of

addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);

Since your Sprite doesn't have a visible area, it will not receive keyboard or mouse input.

Also the STEP() function will cause a stackoverflow because it's infitely recursive.

If you want a main loop that gets called periodically, try using an ENTER_FRAME handler or a Timer.

Something like this:

public function MAIN()
{
    addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
    addEventListener(Event.ENTER_FRAME,STEP);
}

private function STEP(e:Event):void {
    FRAME++;
}

To stop it, do this:

removeEventListener(Event.ENTER_FRAME,STEP);

Not sure why you are using ALL CAPS for some methods and variables. Although it's not a language requirement, all caps are generally reserved for constants. Method names use camelCase. And types use PascalCase (like camelCase, but the first letter is capitalized). So your class would be Main, FRAME would be fram, STEP would be step, etc. You're better off sticking to these common naming schemes, I think.

And another thing. You probably shouldn't be creating a new TextField instance everytime you want to output some text. One textfield will do it in your case, I think. So create and addChild the textfield on some kind of init method that you call when you start your class and then just use the text property of this textfield to write your messages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜