The Layer is a subclass of Node that implements the TouchEventDelegate protocol. If you need to access to inputs from Keyboard, Touch, Mouse or the Accelerometer, you should use a Layer class.
Layers work a bit like Photoshop layers! In your game, you can have a Scene that has one or more Layers as its children for different purposes. One actual game Layer with the game characters in it, a Layer for the scores, one Layer for an in-game menu and another one for the information dialog for example.
Layers can also be modal or non-modal. If you don’t let the touch events pass to the background layers, you will make your layer to be a modal layer. We will see all about the inputs and events in the next section about handling inputs.
Layer Creation
Almost exactly the same way that we created a Scene class, we can create the Layer class! Although, there are two ways to create your layer and scene relationship.
- The first way is to have two separate classes and it is good if you want multiple layers attached to your scene.
MyLayer.h
class MyLayer : public Layer
{
public:
static Layer* createLayer();
virtual bool init();
CREATE_FUNC(MyLayer);
};
MyScene.h
class MyScene : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(MyScene);
};
MyLayer.cpp
#include "MyLayer.h"
Layer* MyLayer::createLayer()
{
auto layer = MyLayer::create();
return layer;
}
bool MyLayer::init()
{
auto sprite = Sprite::create("Box.png");
sprite->setPosition(240, 160);
this->addChild(sprite);
return true;
}
MyScene.cpp
#include "MyScene.h"
#include "MyLayer.h"
Scene* MyScene::createScene()
{
auto scene = MyScene::create();
return scene;
}
bool MyScene::init()
{
auto layer = MyLayer::createLayer();
this->addChild(layer);
return true;
}
- The second way is to combine the Scene and Layer classes. We inherit from Layer but return a Scene instance in the create() method!
CombinedScene.h
class CombinedScene : public Layer
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(CombinedScene);
};
CombinedScene.cpp
#include "KeyboardScene.hpp"
Scene* CombinedScene::createScene()
{
auto scene = Scene::create();
auto layer = CombinedScene::create();
scene->addChild(layer);
return scene;
}
bool CombinedScene::init()
{
auto sprite = Sprite::create("Box.png");
sprite->setPosition(240, 160);
this->addChild(sprite);
return true;
}
The result is just a simple square.
This was a quick introduction to Layer and how to create and use it, which as you saw is very similar to the Scene class.