首页 > 解决方案 > 图层不绘制另一个

问题描述

我正在尝试制作类似于自定义消息框的东西,但 MB 层不想出现在主层(实际上是场景)上。我已经用 2 个文本框实现了非常基本的层(cocos2d::Layer)。我将它添加到场景中

this->addChild(layer);

但实际上什么都没有出现。我已经通过 AudioEngine 添加了音乐并且它可以播放,但我仍然在主场景中什么也看不到。Cocos2d-x 版本是 3.16(最新),我也在 win32 上使用最新的 MSVC。

标签: c++drawingcocos2d-x

解决方案


您需要在场景中添加层作为子层,然后将精灵或其他节点添加到您的层。例如创建继承自 cocos2d::Layer 的测试场景 HelloWorld:

class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
//...

然后使用工厂方法将场景创建定义为:

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

在 init 方法中尝试将您的简单对象添加到继承自 cocos2d::Layer 的 HelloWorld,并且 Layer 是 cocos2d::Scene 的子对象:

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

    // position the label on the center of the screen
    label->setPosition(Vec2(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 1);

在所有这些步骤之后,导演运行了这个场景:

//...
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();

// run
director->runWithScene(scene);
//...

推荐阅读