未定义的Keypress?我该如何定义它

时间:2014-05-05 09:09:27

标签: actionscript-3

我不确定如何定义按键,我有:

public function Shape1(x,y, maxY:uint, maxX:uint) {
        this.x = x;
        this.y = y;
        this.addEventListener(Event.ENTER_FRAME, drop)
        this.addEventListener(KeyboardEvent.KEY_DOWN, keypressed)
        this.addEventListener(KeyboardEvent.KEY_UP, keypressed)
    }

我有这个代码的形状我要移动,它应该在主类中吗?如何定义按键?

2 个答案:

答案 0 :(得分:0)

将事件侦听器添加到舞台。像这样:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keypressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keypressed)

键盘事件将发布到舞台上,并在显示列表中显示。因此,在实际的舞台对象上倾听它们会更好。只要将阶段的引用传递给它,就可以在任何类中添加代码。 我建议有一个单独的类处理键输入 - 检测哪些键是向下/向上。在您的其他对象/类中,只需使用上面建议的键检测类/对象来查看按下了哪些键并运行您想要的特定逻辑。 不要将键盘事件添加到要与之交互的每种类型的对象。

答案 1 :(得分:0)

使用不同的函数调用侦听器并传递其中的引用,例如creatListener(/*refrence*/),因此如果我们假设您有一个名为myMC的引用,那么:

function creatListeners(target:DisplayObject){
    target.addEventListener(Event.ENTER_FRAME, drop)
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keypressed)
    stage.addEventListener(KeyboardEvent.KEY_UP, keypressed)
}
creatListeners(myMC)

function drop(e:Event){
  //your "drop" actions in here
}

function keypressed(e:KeyboardEvent){
  //your actions that you want to be executed if key is up or if key is down
  //by the way if you wish the same function for both listeners do as this..
  //for a versatile code you should separate it into two functions
  //`keyUp_func` and 'keyDown_func' 

  //if you want to specify an action with a certain keyboard press use:
  if (e.keyCode==Keyboard.RIGHT){
      //action when right is pressed
  }
}

function Shape1(x,y, maxY:uint, maxX:uint) {
        this.x = x;
        this.y = y;
}

提示:无论何时添加侦听器,请务必为它们编写删除代码,因此如果您愿意,请使用此新creatListeners替换上述creatListeners

function creatListeners(target:DisplayObject){
    target.addEventListener(Event.ENTER_FRAME, drop)
    target.addEventListener(Event.REMOVED_FROM_STAGE, re_myMC_listeners)
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keypressed)
    stage.addEventListener(KeyboardEvent.KEY_UP, keypressed)
}
function re_myMC_listeners(e:Event){
    myMC.removeEventListener(Event.ENTER_FRAME, drop)
    myMC.removeEventListener(Event.REMOVED_FROM_STAGE, re_myMC_listeners)
    stage.removeEventListener(KeyboardEvent.KEY_DOWN, keypressed)
    stage.removeEventListener(KeyboardEvent.KEY_UP, keypressed)
}