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