Actionscript 3.0键盘事件侦听器未实现该功能

时间:2011-07-05 19:15:55

标签: actionscript-3 function keylistener event-listener

我有这个键盘事件监听器来监听字母A和D的key_Down,但我最终得到了错误:

1119:通过带有静态类型Class的引用访问可能未定义的属性A.

当我使用

function rotate(evt:KeyboardEvent):void
{
    if (evt.keyCode==68) {
    evt.currentTarget.rotation = 90 }
}

function unrotate(evt:KeyboardEvent):void
{
    if (evt.keyCode==65) {
    evt.currentTarget.rotation = 0 }
}

而不是(keyBoard.A和keyboard.D,我不再获取和错误,但旋转图像的功能不起作用。它是否无法识别当前目标并实现该功能或其他什么?

ti.border = true
ti.addEventListener(TextEvent.TEXT_INPUT, onInput);

function onInput(event:TextEvent):void {
  if(ti.text.search('a')!=-1) load_image("http://i54.tinypic.com/anom5d.png", "ottefct");
  else if(ti.text.search('b')!=-1) load_image("http://i53.tinypic.com/2dv7dao.png", "rnd");
  else if(ti.text.search('c')!=-1) load_image("http://i51.tinypic.com/m8jp7m.png", "ssd");
}

var loaded_images:Dictionary = new Dictionary();

function load_image(url:String, id_name:String)
{
  var loader:Loader = new Loader();
  loader.name = id_name;
  var url_req:URLRequest = new URLRequest(url);
  loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadingComplete);
  loader.load(url_req);
}

function onLoadingComplete(evt:Event):void
{
  var img_name:String = evt.currentTarget.loader.name
  var spr_box:Sprite = new Sprite();
  spr_box.addChild(evt.currentTarget.loader);

  spr_box.mouseChildren = false;
  spr_box.doubleClickEnabled = true;

  spr_box.addEventListener(MouseEvent.MOUSE_DOWN, drag);
  spr_box.addEventListener(MouseEvent.MOUSE_UP, drop);
  spr_box.addEventListener(KeyboardEvent.KEY_DOWN, rotate);
  spr_box.addEventListener(KeyboardEvent.KEY_DOWN, unrotate);

  spr_box.width = 124;
  spr_box.height = 180;
  spr_box.x = 430;
  spr_box.y = 425;


  this.addChild(spr_box);
  loaded_images[img_name] = spr_box;
}


function drag(evt:MouseEvent):void
{
  evt.currentTarget.startDrag()
}

function drop(evt:MouseEvent):void
{
  evt.currentTarget.stopDrag()
}

function rotate(evt:KeyboardEvent):void
{
  if (evt.keyCode==Keyboard.D) {
    evt.currentTarget.rotation = 90 
  }
}

function unrotate(evt:KeyboardEvent):void
{
  if (evt.keyCode==Keyboard.A) {
    evt.currentTarget.rotation = 0 
  }
}

3 个答案:

答案 0 :(得分:1)

您需要将KeyBoardEvent附加到舞台而不是对象

stage.addEventListener(KeyboardEvent.KEY_DOWN, rotate);
stage.addEventListener(KeyboardEvent.KEY_DOWN, unrotate);

答案 1 :(得分:0)

甚至更好地使用Fingers

on(stage).keyDown += rotate + unrotate;

请注意,您必须在听众中更改evt.currentTarget,因此它指向您想要轮播的DisplayObject个实例。

更重要的是,有一个stage_keyDownHandler代替rotateunrotate会更清楚:

 stage_keyDownHandler(evt:KeyboardEvent):void
 {
      if (evt.keyCode == Keyboard.D) {
          yourObjToRotate.rotation = 90 
      }
      else if (evt.keyCode == Keyboard.A) {
          yourObjToRotate.rotation = 0 
      }
 }

答案 2 :(得分:0)

单击对象时,会选择其当前目标。但是当你按下键码时,它如何选择目标呢?按键代码时必须定义其实例名称。