Just van Til
Just van Til

Reputation: 71

Linking Enter key to button in Flash game

I'm building a topo-trainer in Adobe Flash with actionscript 3.0. I'm almost done now. I made this "quit" button at the end of the game. You can click it to quit the game now, but I would like the Enter key to react to the quit-button as well. I really tried looking it up on the internet and on stackoverflow, but either my searching skills are not advanced enough or there hasn't been a person with the same problem yet.

I hope somebody knows how to couple the Enter button to a button in Flash. There is no EditText involved.

Thanks for your help,

Justin

Upvotes: 0

Views: 429

Answers (1)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

Let's say you have some code that runs when your games ends:

myQuitBtn.addEventListener(MouseEvent.CLICK, quit, false, 0, true);

function quit(e:MouseEvent):void {
    //do something, we quit the game
}

You could easily listen for a key event by changing it to the following:

myQuitBtn.addEventListener(MouseEvent.CLICK, quit, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false, 0, true);

function keyUpHandler(e:KeyboardEvent):void {
    //Check if the key pressed was the enter key
    if(e.keyCode === 13){   //could also do `e.keyCode === Keyboard.ENTER`
       quit(); 
    }
}

//make the event argument optional so you can call this method directly and with a mouse listener
function quit(e:Event = null):void {
    //remove the key listener
    stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false);

    //do something, we quit the game
}

Upvotes: 2

Related Questions