Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 268
Edward Avatar asked Aug 24 '12 22:08

Edward


3 Answers

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)) )
like image 176
Jinbom Heo Avatar answered Oct 23 '22 05:10

Jinbom Heo


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);
like image 10
superm0 Avatar answered Oct 23 '22 04:10

superm0


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!

like image 8
ekscrypto Avatar answered Oct 23 '22 04:10

ekscrypto