Chapter 4 — Creating Scenes

Previous | Next

Just as movies, television shows, and plays are organized into scenes for the telling of a story, apps are similarly arranged. In this chapter, you'll learn the basics of scene management in Solar2D.

Game Flow

A scene is an isolated view or "page" of the app and everything that the player sees is contained in that scene. When an app starts, you're usually presented with a title/intro scene. From there, you may be able to navigate to a settings scene or proceed to a tutorial. Each level in a game might also be a dedicated scene, depending on the design goals.

This game will have three core scenes:

  1. Menu — Title/intro scene containing various options.
  2. Game — The actual game scene.
  3. High Scores — A list of high scores.

Scene Management

Solar2D uses a system called Composer to handle moving from scene to scene. To make development easier, each Composer scene is a separate Lua file — this helps keep your game more organized.

In this chapter, we're going to make changes to your previous code that will temporarily create errors in the Simulator. For now, you can either ignore the errors or exit the Simulator until you're ready to see the results.

Let's modify the existing project to use Composer:

  1. Within your project folder, make a copy of the main.lua file and rename it to main_original.lua. We will need this original code in the next chapter, so it's important to keep a copy for reference.

  2. Using your chosen text editor, open the main.lua file (not the copy). In this file, erase all of your previous code — remember, you still have the copy to work with later.

  3. In its place, add the following commands:

local composer = require( "composer" )

-- Hide status bar
display.setStatusBar( display.HiddenStatusBar )

-- Seed the random number generator
math.randomseed( os.time() )

-- Go to the menu screen
composer.gotoScene( "menu" )

Let's inspect these commands in a little more detail:

For this command, you don't need to include .lua in the quotation marks because Solar2D already expects the file to have the .lua extension. Thus, you can simply use "menu" to go to the scene that will be contained in menu.lua.

composer.gotoScene( "menu" )

That's it for main.lua — remember to save your changes! Unlike the previous project, this main.lua file is very short because we're only using it to initialize Composer, hide the status bar, seed the random number generator, and move to the menu scene where the action starts.

Chapter Concepts

We've introduced just a couple more concepts in this chapter, both related to Composer:

Command/Property Description
composer.newScene() Creates a new scene object which can be used with the Composer library.
composer.gotoScene() Transitions to a specific Composer scene.