0

我不知道为什么,但由于某种原因,我无法让 InputEngine 类监听 ADDED_TO_STAGE。

package  Input{
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;

public class InputEngine extends Sprite{

    public function InputEngine() {
        addEventListener(Event.ADDED_TO_STAGE, stageAddHandler);
        leftPressed = false;
        rightPressed = false;
        upPressed = false;
        downPressed = false;
    }
    public function stageAddHandler(e:Event)
    {
        trace("worke");
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyIsPressed, false, 0, true);
        stage.addEventListener(KeyboardEvent.KEY_UP, keyIsReleased, false, 0, true);
    }
    public function keyIsPressed(e:KeyboardEvent)
    {
        switch(e.keyCode)
        {
            case Keyboard.LEFT : leftPressed = true; break;
            case Keyboard.RIGHT : rightPressed = true; break;
            case Keyboard.UP : upPressed = true; break;
            case Keyboard.DOWN : downPressed = true; break;
        }
    }
    public function keyIsReleased(e:KeyboardEvent)
    {
        switch(e.keyCode)
        {
            case Keyboard.LEFT : leftPressed = false; break;
            case Keyboard.RIGHT : rightPressed = false; break;
            case Keyboard.UP : upPressed = false; break;
            case Keyboard.DOWN : downPressed = false; break;
        }
    }
    public var leftPressed:Boolean = new Boolean;
    public var rightPressed:Boolean = new Boolean;
    public var upPressed:Boolean = new Boolean;
    public var downPressed:Boolean = new Boolean;

}

}

这是主要的游戏文件:

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

public class System extends Sprite{

    public function System() {
        trace("System created");
        addEventListener(Event.ENTER_FRAME, gameLoop);
        stage.addChild(inputEngine);
        // constructor code
    }
    public function gameLoop(e:Event)
    {
        if(inputEngine.leftPressed == true)
        {
            trace("Left pressed");
        }
    }
    public var inputEngine:InputEngine = new InputEngine();

}

}

由于某种原因,我无法让 InputEngine 初始化键盘侦听器。我在这里做错了什么?

4

1 回答 1

0

根据您对错误的评论,您的问题是您的 System 类的实例尚未添加到显示列表中。没有看到你所有的代码,很难帮助你。

您没有提到您的问题中存在运行时错误。但是,如果我们假设您实际上有一个 inputEngine 实例并且事情正在按照您“预期”的方式发生,那么问题是您的System类实例尚未添加到舞台上。因此... inputEngine 永远不会附加到舞台的显示列表中。

于 2013-10-18T05:13:44.293 回答