为什么我无法在 Cocos2d-x 3.2 中获得重力值

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

本文关键字:Cocos2d-x 为什么      更新时间:2023-10-16

我是cocos2d-x的新手。我试图使用cocos2d-x3.2来构建一个简单的物理游戏,但我遇到了一个问题。一开始,我遵循了教程,并在HelloWorld中添加了这些。h:

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

然后,我在HelloWorld.cpp中添加了这些:

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

然后,我试图在函数init()中获得重力值,如下所示:

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

然后,我运行了它,但程序停止在"Vect g=m_world->getGravity();"它说"0x00C53B44有一个未处理的异常",我不得不中断它。以前有人遇到过同样的问题吗?如果有人能帮我,我真的很感激。

请遵守您的代码

auto layer = HelloWorld::create(); //Calling init Method of Hello World Layer
layer->setPhyWorld(scene->getPhysicsWorld()); // Setting PhysicsWorld instance to the layer

首先调用init()方法,然后将setPhyWorld(scene->getPhysicsWorld())设置为m_world=null。

如果你真的想在init()方法中使用physicsWorld实例,你应该自定义create&init方法,并使用create()方法发送physicsWorld实例。

//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; 
      } 
}

然后

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

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

最后是

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;
}