Search code examples
actionscript-3flashlistenerssimultaneous

AS3 - Avoid Two Buttons being pressed Simultaneously


I am developing a game with a large amount of code. The unfinished version of the game can be found here: http://rainisfalling.co.za/sheep-jump-test/

There are two Key Listeners. One listens for SPACEBAR for the big jump, the other listens for CTRL for the small jump. The problem I am experiencing is that when the two buttons are pressed precisely the same time, both jump actions occur, resulting in a super big jump. (A combination of the two jump heights.)

Here is a simplified version of my code:

addEventListener(KeyboardEvent.KEY_DOWN, bigJump);

function bigJump(e:KeyboardEvent){
//check to see that keycode = SPACEBAR
//code to do the actual jump
//also remove the event listeners for the jumps while in the air
}


addEventListener(KeyboardEvent.KEY_DOWN, smallJump);

function smallJump(e:KeyboardEvent){
//check to see that keycode = CTRL
//code to do the actual jump
//also remove the event listeners for the jumps while in the air
}

Solution

  • Combine jumps into one handler:

    addEventListener(KeyboardEvent.KEY_DOWN, jump);
    
    function jump(e:KeyboardEvent){
           switch( e.keyCode ){
           case 32:  //<Space>
           //Big jump code
           break;
           case 17:  //<Ctrl>
           //Small jump code
           break;
           }
    }