C++ 如何在cocos2d-x中设置图层的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12117250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:53:58  来源:igfitidea点击:

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

c++cocos2d-iphonecocos2d-xcclayer

提问by Edward

I've been writing a game using cocos2d-x and ran into an issue with changing the background color. I found an examplein 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.

我一直在使用 cocos2d-x 编写游戏,但遇到了更改背景颜色的问题。我在 cocos2d 中找到了一个例子,但显然这仅适用于用 Obj-c 编写的 cocos2d。基本上这个想法是使用 CCLayerColor 而不是 CCLayer,并且当构造函数被触发时设置颜色。

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.

有谁知道如何在 cocos2d-x 中更改背景颜色?看起来这很简单,我很确定我错过了一些明显的东西。

回答by Jinbom Heo

2.X or below

2.X 或以下

Extend CCLayerColorinstead of CCLayer. For example,

扩展CCLayerColor而不是CCLayer. 例如,

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 setColormethod from CCLayerColor. For example,

如果你想改变的背景使用setColor的方法CCLayerColor。例如,

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

3.0 or above

3.0或以上

Modify above code like this:

像这样修改上面的代码:

Header file (.h)

头文件 (.h)

class CommonScene : public cocos2d::LayerColor

Source file (.cpp)

源文件 (.cpp)

if( !LayerColor::initWithColor(Color4B(255,255,255,255)) )

回答by superm0

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

在 cocos2d-x v.3.x 中,您可以像这样在 init 方法中添加一个 LayerColor:

auto bg = cocos2d::LayerColor::create(Color4B(53, 53, 53, 255));
this->addChild(bg);

回答by ekscrypto

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!

在你的场景 init() 函数中的某个地方。这样您就不必更改为 LayerColor 并且性能也不会受到影响。干杯!

回答by Jonathan Liu

For Cocos2d-x v3.0

对于 Cocos2d-x v3.0

In *.h

在 *.h

class PlayScene : public cocos2d::LayerColor

In *.cpp

在 *.cpp 中

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

    return true;
}