【问题标题】:cocos2d-x 3.6 PhysicsJointFixed errorcocos2d-x 3.6 PhysicsJointFixed错误
【发布时间】:2015-08-15 03:38:25
【问题描述】:

我是 cococs2dx 的新手,我正在编写涉及 PhysicsJointFixed 的代码。我正在使用 cocos2d-x-3.6。我无法按照指南和 PhysicsTest.cpp 在下面编写的代码编译代码。

我的 GameLayer.h 看起来像:

class GameLayer : public cocos2d::Layer
{
    GameLayer();
    virtual ~GameLayer();

    virtual bool init();

    static Scene* createScene();
    void setPhyWorld(PhysicsWorld* world){m_world = world;}
    CREATE_FUNC(GameLayer);
private:
    PhysicsWorld* m_world;
    ShapeSprite* _square;  //ShapeSprite extends Sprite
    ShapeSprite* _square1;
    PhysicsJointFixed* joint;
    ...
}

GameLayer.cpp 中的 createScene 方法:

Scene* GameLayer::createScene()
{

    auto scene = Scene::createWithPhysics();

    auto layer = GameLayer::create();
    layer->setPhyWorld(scene->getPhysicsWorld());

    scene->addChild(layer);

    return scene;
}

然后在 GameLayer::init() 中

bool GameLayer::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
...
...

_square =  ShapeSprite::gameSpriteWithFile("square.png");
auto squareBody = PhysicsBody::createBox(Size(200,200));
_square->setPhysicsBody(squareBody);
_square->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height     * 0.7f));

_square1 =  ShapeSprite::gameSpriteWithFile("square1.png");
auto squareBody1 = PhysicsBody::createBox(Size(100,100));
_square1->setPhysicsBody(squareBody1);
_square1->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height * 0.7f));

this->addChild(_square);
this->addChild(_square1);

joint = PhysicsJointFixed::construct(_square->getPhysicsBody(), _square1->getPhysicsBody(),Vec2(100,100));

this->getScene()->getPhysicsWorld()->addJoint(joint);

return true;

}

代码给出EXC_BAD_ACCESS错误就行 this->getScene()->getPhysicsWorld()->addJoint(joint); 因为,this->getScene()->getPhysicsWorld() 返回 NULL。

请指教,我怎样才能避免错误。任何建议表示赞赏。提前致谢。

【问题讨论】:

标签: cocos2d-x cocos2d-x-3.0


【解决方案1】:

出现此错误是因为在init() 期间您的自定义图层尚未添加到场景中。一种可能的解决方案是覆盖onEnterTransitionDidFinish() 并在那里添加关节。在GameLayer.h 中添加:

virtual void onEnterTransitionDidFinish();

并将关节添加代码移动到 GameLayer.cpp,如下所示:

void GameLayer::onEnterTransitionDidFinish() {
    joint = PhysicsJointFixed::construct(_square->getPhysicsBody(), _square1->getPhysicsBody(),Vec2(100,100));

    this->getScene()->getPhysicsWorld()->addJoint(joint);
}

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    相关资源
    最近更新 更多