How to set background color of layer in cocos2d-x?
Asked Answered
M

4

15

I've been writing a game using cocos2d-x and ran into an issue with changing the background color. I found an example in cocos2d, but apparently this only applies to cocos2d which is written in Obj-c. Basically the idea is to use a CCLayerColor instead of CCLayer, and when the constructor gets fired set the color.

Does anyone know how to change the background color in cocos2d-x? Seems like it would be pretty simple, I'm pretty sure I'm missing something obvious.

Mach answered 24/8, 2012 at 22:6 Comment(0)
O
33

2.X or below

Extend CCLayerColor instead of CCLayer. For example,

class CommonScene : public cocos2d::CCLayerColor
{
public:
...
}

Initialize with this code:

bool CommonScene::init()
{
    //////////////////////////////
    // 1. super init first
    if( !CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)) ) //RGBA
    {
        return false;
    }
    ...
}

If you want to change background use the setColor method from CCLayerColor. For example,

this->setColor(ccc3(255, 255, 255));

3.0 or above

Modify above code like this:

Header file (.h)

class CommonScene : public cocos2d::LayerColor

Source file (.cpp)

if( !LayerColor::initWithColor(Color4B(255,255,255,255)) )
Oedipus answered 25/8, 2012 at 12:58 Comment(1)
I am also facing this issue. How did you solve it? If I change according to this. I am getting error as in below question #17588036Bromeosin
D
10

In cocos2d-x v.3.x, you can add a LayerColor inside the init method like this:

auto bg = cocos2d::LayerColor::create(Color4B(53, 53, 53, 255));
this->addChild(bg);
Deadandalive answered 11/9, 2015 at 9:47 Comment(1)
By this way, cocos2d-x displays wrong color. If i use LayerColor::create(Color4B(255, 0, 0, 255)) , the displayed color is fb0007 not ff0000Shipentine
A
8

The easiest way I could locate that does not impact performance, is to simply do:

glClearColor(1.0,1.0,1.0,1.0);

Somewhere in your Scene init() function. This way you do not have to change to a LayerColor and performance is not affected either. Cheers!

Americanism answered 31/5, 2014 at 5:38 Comment(0)
M
8

For Cocos2d-x v3.0

In *.h

class PlayScene : public cocos2d::LayerColor

In *.cpp

bool PlayScene::init()
{
    if ( !LayerColor::initWithColor(Color4B(255, 255, 255, 255) )) {
        return false;
    }

    return true;
}
Millimicron answered 11/7, 2014 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.