2015-08-15 30 views
0

我是cococs2dx的新手,我正在研究涉及PhysicsJointFixed的代碼。我正在使用cocos2d-x-3.6。我無法按照以下指導方針和PhysicsTest.cpp所述編寫代碼。cocos2d-x 3.6 PhysicsJointFixed error

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

的createScene方法GameLayer.cpp:

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。

請指教,我該如何避免錯誤。任何建議表示讚賞。提前致謝。

+0

更多的建議,你應該對這些問題的答案閱讀:http://stackoverflow.com/questions/28486310 /如何對接入的物理世界,同層/ 38573485#38573485 – Joseph

回答

0

發生此錯誤是因爲您的自定義圖層在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); 
}