我正在使用三个类,并且为了便于阅读而缩短了三个类,省略了包和导入。MainClass
是我的文档类,Player
是链接到影片剪辑KeyHandler
的类,是我用来包含按键功能的类。首先,代码..
public class TestMain extends Sprite
{
public var keyHandler:KeyHandler = new KeyHandler();
public var timer:Timer = new Timer(30);
public var player:Player = new Player();
public function TestMain()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler.KeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler.KeyRelease);
timer.addEventListener(TimerEvent.TIMER, onTick);
timer.start();
stage.addChild(player);
}
public function onTick(timerEvent:TimerEvent)
{
player.Move();
}
}
玩家等级..
public class Player extends Sprite
{
public var keyHandler:KeyHandler = new KeyHandler();
public function Player()
{
}
public function Move():void
{
trace("this works");
if (keyHandler.upKeyIsPressed)
{
trace("this doesnt work")
}
}
}
KeyHandler 类..
public class KeyHandler extends Sprite
{
public var upKeyIsPressed:Boolean = false;
public function KeyHandler()
{
}
public function KeyPress(keyboardEvent:KeyboardEvent)
{
if (keyboardEvent.keyCode == Keyboard.UP)
{
upKeyIsPressed = true;
}
}
public function KeyRelease(keyboardEvent:KeyboardEvent)
{
if (keyboardEvent.keyCode == Keyboard.UP)
{
upKeyIsPressed = false;
}
}
}
按住向上键不会跟踪任何内容,但Move
函数会跟踪。我应该做KeyHandler
静态,还是有一个简单的修复?这是不好的做法吗?