简体   繁体   中英

AS3: Multiple options in one key and preventing multiple key presses

I have a "pause function" in my AS3 code, the problem is that i can't figure the logic necessary to give the letter "P" the capacity to pause and unpause and at the same time limit the number of presses to one at a time. My code so far (working ,yes, but without the "one press at a time" limit).

    public function PauseDown(event:KeyboardEvent):void
    {
        if (event.keyCode == Keyboard.P)
        {
            pause = true;
            trace ("apreté pausa");
            pausa();
        }
    }
    public function pausa():void 
    {
        trace ("pausa");
        if (pause == true && paused == false)
        {
            paused = true;
            backgroundLvL1.removeEventListener(Event.ENTER_FRAME,update);
        }
        else if(pause == true && paused == true)
        {
            paused = false;
            backgroundLvL1.addEventListener(Event.ENTER_FRAME,update);
        }
    }

Your 'PauseDown' function should probably be called something else, because it's going to be called whenever ANY key is pressed; Something like 'keyPressed' is probably more descriptive.

If you want to have only ONE key acknowledged as the most recently pressed key, I would set a variable (eg _currentKeyCode) to the event.keyCode in the 'keyPressed' function. Then, in your game loop function you can check the value of _currentKeyCode and have the game respond accordingly.

In the 'keyPressed' function you could also still include your test to see if 'P' has been pressed.
Note that you should also have a 'keyReleased' function, triggered on a KeyBoardEvent.KEY_UP event. This could check if _currentKeyCode == the event.keyCode and, if so, set _currentKeyCode to -1. Then, in your game loop, -1 would signify no key presses.

One last, slightly irrelevant, thing: In the 'pausa' function you don't need to check if 'pause == true' because the pausa function is only called when pause == true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM