gpt4 book ai didi

c++ - 为什么在 Cocos2d-x 3.2 中无法获取重力值

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:13 26 4
gpt4 key购买 nike

我是 cocos2d-x 的新手。我试图使用 cocos2d-x 3.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实例,你应该自定义HelloWorld层的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;
}

关于c++ - 为什么在 Cocos2d-x 3.2 中无法获取重力值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com