Cocos2D-x Tutorials Part 6: Switching between scenes
In this tutorial we are going to see how to create a menu for our game that will let us switch between different game scenes.
There are multiple ways to design a menu in cocos2d-x. In the default generated code we can see how to create a menu with sprites. Here we will see how we can create our menu with LabelTTF or simple text. The process is quite simple. Lets see some code:
Go to AppDelegate.cpp and change the Line 33 :
auto scene = MenuScene::createScene();
Also include these 2 lines after Line 2:
We have all the code in our hand, so lets see what the code is doing for us:
First of all, let us write the steps to create a menu:
- Create a LabelTTF object. (MenuScene.cpp line 31 and 32)
- Create a MenuItemLabel with the label object with a callback attached. (Line 34 and 35)
(nowis a good time to see how C++11 lambda functions work if you are not familiar with them. They are mind blowing! )
- Create a Menu object with the MenuItemLabel object. (Line 37)
- Add the Menu object with the layer. (Line 39)
It’s just a 4 step process !!!
At line 5 in MenuScene.cpp there is a function. It actually computes the linear interpolation between 2 points. Its completely optional and has nothing to with this tutorial, but I wanted to share it because its an important concept for game development math. So may be you want to learn it if you haven’t already.
At line 34 of MenuScene.cpp we called a method pushScene() our Director singleton. What is does is simple: Director class has a property called _sceneStack which is a
cocos2d::Vector<Scene > object. pushScene() pushes our
TankMove::createScene() object to the stack and also assigns our scene as the *_nextScene** which is also a Director class property. _nextScene is the running scene for the next frame.
Also we have passed
Ref* sender as parameter in our lambda function. if you are using earlier versions of cocos2d-x, then you have to use Object* instead of Ref*
At line 20 of Scene1.cpp we called anothefunction popScene() which actually pops the current scene out of the _sceneStack and assigns the previous scene to the _nextScene if any.
Lets run the code and see what happens:
if we click on Scene_1 or Scene_2 we go to the Scene1 (TankMove class) and by clicking the Back we return to our menu page.
In the next tutorial we will see how infinite scrolling works. Also we will introduce ParallaxNode hopefully.