Android back button usage in Stencyl

By default the back button of Android device sends the active application to back. However, in many mobile games back button is used e.g. to return to the menu (or any equivalent action). This is possible in Stencyl also, but you have to configure the behavior first to match your needs. Here are simple steps to do it:
  1. Go Settings -> Mobile -> User Input
  2. Activate "Override Back Button". This makes back button to act like escape key
  3. Go Settings -> Controls. Check escape key bindings (name: Escape, Key:Escape)
  4. Open your game scene and go to "events" tab (or edit behavior)
  5. Create keyboard event for escape key, as shown in Figure1 below (Add Event -> Input -> Keyboard). Set control as "escape".
  6. Add transition block and fill in your menu scene name + other required information
Figure1: Keyboard event for escape key

That's it! Now you can exit from your play scene to menu screen. 

But wait, did you forgot something? Yes, Since the default action of back button is now disabled, you can't exit the game normal way. So we probably have to do something for this. Here is one way to implement exit behavior with nme.lib.exit(); function from NME framework:
  1. Open your main menu (or any scene you might want to exit the game)
  2. Add "Import" block to the scene: Add event -> Advanced -> Custom Import
  3. Write "import nme.Lib;" to the Code field as shown in Figure2 (imports NME framework)
  4. Create keyboard event for escape key (Add Event -> Input -> Keyboard). Set control as "escape".
  5. Add code block to the event (Select from palette: Flow -> Advanced -> Code )
  6. Write following to code block (see Figure3):
    #if android
This code makes game to exit when back button is pressed on Android device (not active on other platforms)
Figure2: The "Import" block for main menu (or equivalent)

Figure3: Code that is executed when escape is pressed

Now we should have nicely working back button in our Android game, assuming I did not forget anything....



Popular posts from this blog

Unity3D: Convert Seconds to hh:mm:ss Format

Construct 2: if-then-elseif-else statement

Issue with Unity3D: "Found plugins with same names, and ."