Wednesday, September 25, 2013

How to handle Back button event in Starling Framework?

When creating mobile games featuring intensive user interactions in Android, it is normal to notice that the players have a higher tendency to touch the back button (or the menu button) which is outside the region of your designed GUI. By default, the back button on the Android devices would immediately minimize your games' UI, without any warning. This is especially unfavorable when the player who intends to 'go back' to the previous game map, finally ends up having his home page popped up, and the game play experience is ruined.

Hence, it is a good practice to handle Back button event properly in Starling Framework. Below shows the necessary code snippets:

1. Import flash UI keyboard and keyboardEvent:
import flash.ui.Keyboard;
import starling.core.Starling;

2. Add an event listener in your main starling class:
Starling.current.nativeStage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);

3. Handle the Back button event with e.preventDefault function:
private function keyPressed(e:KeyboardEvent):void
     if(e.keyCode == Keyboard.BACK)

          trace("Back button is pressed");


1 comment:

  1. This was very useful. Huge thanks for sharing! :)