ACTIONSCRIPT 3.0无缝键盘事件

时间:2014-04-08 05:10:35

标签: actionscript-3

我迷路了,这对初学者来说并不奇怪。我试图执行一个平滑无缝的键盘方向命令。当按住键时会发生问题,这会产生延迟并像运动那样分段。代码在下面,请在此= =

var dx:Number = 0;


paddle.addEventListener(Event.ENTER_FRAME, motion);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);


function motion (event:Event):void{
paddle.x = dx
}

function keyPressed(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){ 
     dx -= 20;
  }

if(event.keyCode == Keyboard.RIGHT){
    dx += 20;
  } 
} 

2 个答案:

答案 0 :(得分:1)

您基本上可以跟踪KEY_DOWN上按键的时间并在KEY_UP上重置。然后,在ENTER_FRAME中,检查按键是否按下,然后移动划水板。

这样的事情:

var isLeftPressed:Boolean = false;
var isRightPressed:Boolean = false;

stage.addEventListener( KeyboardEvent.KEY_DOWN, this._onKeyDown );
stage.addEventListener( KeyboardEvent.KEY_UP, this._onKeyUp );
paddle.addEventListener( Event.ENTER_FRAME, this._onEnterFrame );

// called when a key is pressed
function _onKeyDown( e:KeyboardEvent ):void
{
    if( e.keyCode == Keyboard.LEFT )
        isLeftPressed = true;
    if( e.keyCode == Keyboard.RIGHT )
        isRightPressed = true;
}

// called when a key is released
function _onKeyUp( e:KeyboardEvent ):void
{
    if( e.keyCode == Keyboard.LEFT )
        isLeftPressed = false;
    if( e.keyCode == Keyboard.RIGHT )
        isRightPressed = false;
}

// called every frame
function _onEnterFrame( e:Event ):void
{
    // get our direction based on what key is pressed, and move our paddle
    var dirX:int    = ( isLeftPressed ) ? -1 : ( isRightPressed ) ? 1 : 0;
    paddle.x        += 20 * dirX;
}

这可以很容易地针对任何键进行推广(使用Vector.<Boolean>作为索引保持keyCode) - 查看普通要点的PushButtonEngine KeyboardManagerhttps://github.com/PushButtonLabs/PushButtonEngine/blob/PBE2/src/com/pblabs/input/KeyboardManager.as

答案 1 :(得分:0)

当用户按下某个键时,您应移动该对象,直到调度KeyboardEvent.KEY_UP事件以了解用户何时释放该键。以下是您正在寻找的示例: Moving Movieclips using Keys with Acstionscript 3

我希望它对你有所帮助。祝你好运!