TGB/Tutorials/Pause Game

From TDN

Introduction

Tested on TGB 1.7.2

This tutorial shows you how to pause your game when a user navigates away from your game.

Note: This if you plan to distribute you game on game distribution sites, many of them require a way to pause the game when the user navigates away.

Let's get started!

Update Game.cs

When a player navigates away from your game, the following script will pause your game and turn off the sound for your game (in our case, it turns down the volume to 0).

  1. Navigate to [project name]\game\gameScripts.
  2. Open game.cs in a text editor, and paste in the following code at the bottom of the file:
    //---------------------------------------------------------------------------------------------
    // Pause game when player navigates away from game window
    //    -isFocused: 0=game window not focus, 1=game window is focus
    //---------------------------------------------------------------------------------------------
    function onWindowFocusChange(%isFocused)
    {
       // pause game
        if (!%isFocused)
            pauseWindow(1);
            
       // unpause game
        else
            pauseWindow(0);
    }
    
    //---------------------------------------------------------------------------------------------
    // Pause or unpause the game (when alt+tab away from game window).
    //---------------------------------------------------------------------------------------------
    function pauseWindow(%state)
    {      
        %scene = Scenewindow2d.getSceneGraph();       
        %result = (%state == 1) ? true : false;
        
        // pause game (only if the player hasn't paused the game)
        if (!$pauseingame)
        {
          %scene.setScenePause( %result ); 
          $paused = %state;
          echo("Paused: " @ %result);        
        }
        
        // turn music off when paused
        if (%state)
        {
          alxSetChannelVolume($GuiAudioType, 0);
          echo("Music Off");          
        }
        
        // turn music on when upaused (and music option on)
        else if ($music)
        {
          alxSetChannelVolume($GuiAudioType, 1);
          echo("Music On");           
        }
    }
    
    
  3. Save 'game.cs' and close the file.


    Edit: Fixed .gui to .cs