Box2d在cocos2d-x下基本使用

來源:互聯網
上載者:User

要使用Box2d,首先要建立世界,有了世界才有Box2d裡類比的一切。

建立世界:

b2Vec2 gravity(0.0f,-10.0f);

world= new b2World(gravity);

bool doSleep = true;

world->SetAllowSleeping(doSleep);

world->SetContinuousPhysics(true);

其次類比物理世界要有一個邊界,Box2d會針對邊界內的地區進行類比,跑出邊界外的剛體(或叫精靈)會被凍結,停止類比。所以一般邊界的大小比視窗要大一些,合適就好,適合的類比效果和效能將更好。

設定邊界:

b2BodyDef groundBodyDef;

groundBodyDef.position.SetZero();

b2Body *groundBody = world->CreateBody(&groundBodyDef);


b2EdgeShape
groundBox;

groundBox.Set(b2Vec2(0,0),b2Vec2(winSize.width/PTM_RATIO,0));

groundBody->CreateFixture(&groundBox,0);

groundBox.Set(b2Vec2(0,0),b2Vec2(0,winSize.height/PTM_RATIO));

groundBody->CreateFixture(&groundBox,0);

groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO));

groundBody->CreateFixture(&groundBox,0);

groundBox.Set(b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,0));

groundBody->CreateFixture(&groundBox,0);

將精靈綁定到Box2d裡的剛體上,精靈將隨著Box2d的類比而不斷的更新位置和效果等等。

實現精靈綁定:

b2BodyDef
bodyDef;

bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(point.x/PTM_RATIO, point.y/PTM_RATIO);

bodyDef.userData =pSprite;

b2Body *body= world->CreateBody(&bodyDef);


b2PolygonShape shapeBox;

shapeBox.SetAsBox(.5f,.5f);

b2FixtureDef fixtureDef;

fixtureDef.shape = &shapeBox;

fixtureDef.density = 1.0f; //密度係數

fixtureDef.friction = 0.3f; //摩擦係數

body->CreateFixture(&fixtureDef);

最後實現物理類比,並更新精靈的位置或效果。

void update(float dt)  
{  
    world->Step(dt, 8, 1);
    for(b2Body *b=world->GetBodyList(); b; b=b->GetNext())
    {
        if(b->GetUserData()!=NULL)
        {
            CCSprite *sprite=(CCSprite*)b->GetUserData();
            
            sprite->setPosition(ccp(b->GetPosition().x*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
            sprite->setRotation((-1)*CC_RADIANS_TO_DEGREES(b->GetAngle()));
        }
    }
}

參考博文(http://blog.csdn.net/cq361106306/article/details/7933128)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.