我想知道如何从as3中的单独类中获取键盘输入。我有一个类将使用箭头键移动,但它需要在hero
类中如何从主函数调用移动函数?
答案 0 :(得分:0)
您通常会从舞台上收听键盘事件,因此处理此问题的最佳方法可能是将您需要的特定键盘逻辑添加到Hero类本身。
您可以侦听Hero中的ADDED_TO_STAGE和REMOVED_FROM_STAGE事件,以触发何时添加和删除键盘事件侦听器。
一个基本的例子可能是这样的:
public class Hero extends Sprite
{
// Constructor
public function Hero()
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
// Event handlers
protected function onAddedToStage( event:Event ):void
{
this.removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
this.addEventListener( Event.REMOVED_FROM_STAGE, onRemovedFromStage );
this.stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyDown );
this.stage.addEventListener( KeyboardEvent.KEY_UP, onKeyUp );
}
protected function onRemovedToStage( event:Event ):void
{
this.addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
this.removeEventListener( Event.REMOVED_FROM_STAGE, onRemovedFromStage );
this.stage.removeEventListener( KeyboardEvent.KEY_DOWN, onKeyDown );
this.stage.removeEventListener( KeyboardEvent.KEY_UP, onKeyUp );
}
protected function onKeyDown( event:KeyboardEvent ):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
// Start movement
break;
case Keyboard.RIGHT:
// Start movement
break;
}
}
protected function onKeyUp( event:KeyboardEvent ):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
// Stop movement
break;
case Keyboard.RIGHT:
// Stop movement
break;
}
}
}