check keyboard state without using KeyboardEvent in AS3

。_饼干妹妹 提交于 2019-12-10 20:03:36

问题


Is it possible to check for pressed keys without using the KeyboardEvent?

I have an ENTER_FRAME event setup called enterFrameHandler and I want to check within the function enterFrameHandler if any keys are pressed.

normally when using a KeyboardEvent I could check for keys easily using a switch that checks the KeyCode of the event, but in an ENTER_FRAME event this isn't possible for me.

Is there any other way of checking the keyboard's state within the ENTER_FRAME event?

UPDATE: I found this AS2 script:

onClipEvent (enterFrame) {
    if (Key.isDown(Key.LEFT)) {
        _x -= power;
    }
    if (Key.isDown(Key.RIGHT)) {
        _x += power;
    }
    if (Key.isDown(Key.UP)) {
        _y -=power;
    }
    if (Key.isDown(Key.DOWN)) {
        _y +=power;
    }
}

This seems to be doing what I want, but it's in AS2, does anyone know how to 'translate' this into AS3?


回答1:


Store key states in a dictionary or object:

stage.addEventListener(KeyboardEvent.KEY_UP, keyHandleUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandleDown);

private var hash:Object = {};

private function keyHandleUp(event:KeyboardEvent):void {
    delete hash[event.keyCode];
}

private function keyHandleDown(event:KeyboardEvent):void {
    hash[event.keyCode] = 1;
}

private function isKeyDown(code:int):Boolean {
    return hash[code] !== undefined;
}



回答2:


The short answer is no Why don't you want to use a KeyboardEvent event listener?




回答3:


With a KeyboardEvent.KEY_DOWN listener added to the stage, keeping the key pressed works just fine, so there's no need for the ENTER_FRAME.

private function keyDownHandler(evt:KeyboardEvent):void
{
    switch(evt.keyCode)
    {
        case 37: //left key
                trace("Move left");
            break;
        case 38: //up key
            trace("Move up");
            break;
        case 39: //right key
            trace("Move right");
            break;
        case 40: //down key
            trace("Move down");
            break;
    }

}


来源:https://stackoverflow.com/questions/2613196/check-keyboard-state-without-using-keyboardevent-in-as3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!