使用addChild()时,Flash as3类不会调用ADDED_TO_STAGE事件

时间:2013-10-18 03:17:54

标签: actionscript-3 flash

我不知道为什么,但由于某种原因,我无法让我的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来初始化键盘监听器。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

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

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