Time for action – changing screens after the game is over

Now that we have renamed our game file, let's add in a scene transition so that our game is not stuck at the Game Over screen once game play is over. To change the screen, perform the following steps:

  1. In our maingame.lua file, add in a new variable called local menuBtn, where all the other variables are initialized in the beginning of the code. Inside the callGameOver() function, add the following lines after the highScoreText code:
        local onMenuTouch = function( event )
          if event.phase == "release" then
            audio.play( btnSound )
            composer.gotoScene( "mainmenu", "fade", 500  )
    
          end
        end
    
        menuBtn = ui.newButton{
          defaultSrc = "menubtn.png",
          defaultX = 60,
          defaultY = 60,
          overSrc = "menubtn-over.png",
          overX = 60,
          overY = 60,
          onEvent = onMenuTouch,
          id = "MenuButton",
          text = "",
          -- Can use any font available per platform
          font = "Helvetica",   
          textColor = { 255, 255, 255, 255 },
          size = 16,
          emboss = false
        }
    
        menuBtn.x = 100; menuBtn.y = 260
    
        gameGroup:insert( menuBtn )
    Time for action – changing screens after the game is over

In order to transition out of the game over screen, a menu button was created to change scenes. Inside the onMenuTouch() function, upon the release of the button, we called composer.gotoScene( "mainmenu", "fade", 500 ). This will allow the application to transition to the main menu in 500 milliseconds using a fade, which we will create later on in this chapter.

Now that you're well aware of how the Composer API works with changing scenes and using UI buttons to transition between them, how about creating a button that restarts the game after the game over screen appears? So far, the application allows the user to go back to the menu screen once the game has reached an end.

Within the callGameOver() function, a new local function needs to be created that will run an event using the UI button system to change scenes with Composer. Note that you can't call the same scene over if you're currently in it.