Cocos2d-x:当设置PhysicsWorld时,一些精灵会变得不可见

Cocos2d-x : some sprites become invisible when a PhysicsWorld is set

本文关键字:精灵 设置 PhysicsWorld Cocos2d-x      更新时间:2023-10-16

我目前正在尝试用cocos2d-x引擎制作一款游戏。正如我想象的那样,这个游戏需要一个滚动的背景。然后我在一张表中创建了两个背景精灵:

bool HelloWorld::init()
{
    ///////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    //creating "first" background 
    background[0] = Sprite::create("fond.png");
    background[0]->setPosition(0, 0);
    background[0]->setAnchorPoint(Vec2(0, 0));
    this->addChild(background[0]);
    //creating "second" background
    background[1] = Sprite::create("fond.png");
    background[1]->setPosition(background[0]->getContentSize().width, 0);
    background[1]->setAnchorPoint(Vec2(0, 0));
    this->addChild(background[1]);
    this->scheduleUpdate();
    return true;
}

然后我让它们以这种方式滚动,在一个更新功能中:

void HelloWorld::update(float delta)
{
    for(int i = 0 ; i < 2 ; i++) { //scrolling background
        if (background[i]->getPositionX() <= 0) {
            background[i]->setPositionX(background[i]->getPositionX()-800*delta);
            background[1-i]->setPositionX(background[1-i]->getContentSize().width+(background[i]->getPositionX()));
        }
    }
}

所以,现在,我有了基本的init()和update()函数,这很好:)。现在我需要执行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;
}

然后它就完美地工作了!但遗憾的是,在我剩下的游戏中,我需要物理(你知道,碰撞之类的),所以我需要把这个函数改成至少这个:

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::createWithPhysics();
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();
    // add layer as a child to scene
    scene->addChild(layer);
    // return the scene
    return scene;
}

问题来了:当我添加PhysicsWorld(就像那里一样)时,背景[1]变得不可见,就像当他必须出现在屏幕上时,我有一个漂亮的黑色屏幕,直到背景[0]出现。我觉得几乎什么都试过了,但找不到任何解决方案。。。有人知道我应该做什么吗?

p.S:我现在在Linux平台上做了所有的测试,我有cocos2d-x3.4版本。

我不确定你是否在项目中使用SpriteBuilder或CocosStudio,但在与Cocos2d一起使用的多个GUI中,我看到当你设置一些精灵相对于屏幕大小的位置而不是使用点或UI点时,一旦你在代码中移动精灵,通常会产生很多错误。从加载代码的那一刻起,尝试在代码中设置相对位置,或者不要使用相对初始定位来移动正在使用的GUI中的精灵。