Aiwen Wei
Aiwen Wei

Reputation: 11

Why I couldn't get gravity value in Cocos2d-x 3.2

I'm new with cocos2d-x. I was trying to use cocos2d-x 3.2 to build a simple physics game, but I got a problem. At the beginning, I followed the tutorial and added these in HelloWorld.h:

private:
    PhysicsWorld* m_world;
public:
    void setPhyWorld(PhysicsWorld* world){ m_world = world; }

Then, I added these in HelloWorld.cpp:

Scene* HelloWorld::createScene()
{
    auto scene = Scene::createWithPhysics();
    auto layer = HelloWorld::create();
    layer->setPhyWorld(scene->getPhysicsWorld());
    scene->addChild(layer);
    return scene;
}

Then, I tried to get the gravity value in function init() like this:

bool HelloWorld::init()
{
    Vect g=m_world->getGravity();
    if ( !Layer::init() )
    {
        return false;
    }
    Size visibleSize = Director::getInstance()->getVisibleSize();
    return true;
}

Then, I ran it, but the program stopped at "Vect g=m_world->getGravity();" It said that "0x00C53B44 had an Unhandled Exceptions", and I had to interrupt it. Did anybody have the same problem before? I really appreciate if anyone can help me.

Upvotes: 1

Views: 771

Answers (1)

Shoaib
Shoaib

Reputation: 2294

Please observe your code

auto layer = HelloWorld::create(); //Calling init Method of Hello World Layer

layer->setPhyWorld(scene->getPhysicsWorld()); // Setting PhysicsWorld instance to the layer

the init() method is called first and then you are setting setPhyWorld(scene->getPhysicsWorld()) so m_world = null.

If you really want physicsWorld instance in the init() method, you should customize the create & init method of HelloWorld layer and send physicsWorld instance with create() method.

//This code above header class of HelloWorld
#define CUSTOM_CREATE_FUNC(__TYPE__) \
static __TYPE__* create(PhysicsWorld* world) \
{ \
    __TYPE__ *pRet = new __TYPE__(); \
    if (pRet && pRet->init(world)) \
    { \
       pRet->autorelease(); \
       return pRet; \
     } \
     else \
     { \
        delete pRet; \
        pRet = NULL; \
        return NULL; \
      } \
}

and then

CUSTOM_CREATE_FUNC(HelloWorld); // in the header class, instead of CREATE_FUNC(HelloWorld)
virtual bool init(PhysicsWorld* world);

and

auto layer = HelloWorld::create(scene->getPhysicsWorld()); // in the createScene() Method 

and finally

bool HelloWorld::init(PhysicsWorld* world)
{
   m_world = world;
   Vect g=m_world->getGravity();
   if ( !Layer::init() )
   {
      return false;
   }
   Size visibleSize = Director::getInstance()->getVisibleSize();
   return true;
}

Upvotes: 1

Related Questions