Reza Ghobadinic

Scene

Scenes are the states or pages of a game. They are responsible for running the logic of the game and rendering the things that the player sees in real-time. Each game needs at least one scene to start with.

We define different scenes in a game for different states and we switch or transition from one scene to another to control the flow of the game application.

For example imagine in a game we have:

When our game application starts, first we call the Logo Scene and after a few seconds, we go to the Main Menu Scene. From there if the user chooses to play from the main menu, we switch to the Game Scene or if he chooses to change the settings, we switch to the settings scene. Inside the Game Scene, when the games ends by the player either winning or losing, we show the Game Over Scene. You get the idea…!

From the technical aspect, the Scene class is a subclass of Node and they are almost identical to each other except that the anchor point of the Scene is at the center of the screen by default. Scene also creates a default camera for you.

If we don’t need to use touch and accelerometer, we create all our game Nodes (including Sprites, Labels, etc…) and parent them to the Scene. Otherwise, we parent everything to a Layer instance (which we will see in later posts) to receive touch and accelerometer data and then we parent that Layer to the scene.

Creating a Scene instance is the same as creating any Node, but most of the time, that is not how we use it! Instead, we create a class from scratch that inherits the Scene class and let it create its objects. Then we create instances of that Scene class that we just created.

When you create a new cocos2d-x project using the new command, your project already has a default Scene called HelloWorld which is inherited from the Scene class and then some functionality is added to it to draw what you see on the screen! That is inside the HelloWorldScene.h and HelloWorldScene.cpp files in your project. Go have a look!

In your AppDelegate class you can see that a HelloWorld scene is created and used as the start scene. The first scene always starts by calling runWithScene() method of the director class.

// Inside AppDelegate::applicationDidFinishLaunching() method of AppDelegate.cpp

// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();

// run
director->runWithScene(scene);

So far in this blog, we have been altering this default scene for our Node and Sprite examples and didn’t need to create a new one ourselves. But in the following posts we will create some scenes and will use transitions to go from one to another.

Lets get into business:

Exit mobile version