[SOLVED]V3.16 - Scene::createWithPhysics() can not show Sprite

[SOLVED]V3.16 - Scene::createWithPhysics() can not show Sprite
0.0 0

#1

Hi,

I just download V3.16 and create a new project for test.

cocos new -l cpp

I found some strange situation

  1. After project create, I just compile and run, then it shows correct screen.
  2. I modify HelloWorldScene.cpp
...
    Scene* HelloWorld::createScene()
    {
        auto scene = HelloWorld::createWithPhysics();
        
        scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
        
        return scene;
    }
...

it shows blank screen.


3. Then I try to inherit from Layer, not like new template inherit from Scene.
It will show correct screen too.

HelloWorldScene.cpp

...
Scene* HelloWorld::createScene()
{
    auto scene = Scene::createWithPhysics();
        
    auto layer = HelloWorld::create();

    scene->addChild(layer);
    
    return scene;
}

// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
    printf("Error while loading: %s\n", filename);
    printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}

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

HelloWorldScene.h

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

    virtual bool init();
...

So, is there anything I miss to create a scene with Physics?

thank you.


#2

I can test this soon.


#3

In fact, everything works correctly.

Since CREATE_FUNC overrides Scene::create() in the default template then HelloWorld::create() creates an object of the HelloWorld class, and calls the HelloWorld::init().
But HelloWorld::createWithPhysics() creates an object of the Scene class, and calls the Scene::initWithPhysics(). In this case, the HelloWorld::init() was never called.

In the third case, the HelloWorld::init() is called, so everything is fine.


#4

It’s funny. I always remove this and just write my own.


#5

Why? Is not it convenient?


#6

I think when I started with v2.2.x, I was in the mode to learn details first. Now it is habit.


#7

Thank you, maybe I should write by self too, not just use CREATE_FUNC :slight_smile: