Box2D世界有無限大小。你不能限制世界,但你可以在Box2D世界中創建一個封閉某個區域的形狀。
下面介紹如何創建一個在屏幕周圍放置形狀的物體和形狀,以便物體不會離開屏幕。通過更改角座標以適應您需要的任何內容很容易:
// for the screenBorder body we'll need these values
CGSize screenSize = [CCDirector sharedDirector].winSize;
float widthInMeters = screenSize.width/PTM_RATIO;
float heightInMeters = screenSize.height/PTM_RATIO;
b2Vec2 lowerLeftCorner = b2Vec2(0, 0);
b2Vec2 lowerRightCorner = b2Vec2(widthInMeters, 0);
b2Vec2 upperLeftCorner = b2Vec2(0, heightInMeters);
b2Vec2 upperRightCorner = b2Vec2(widthInMeters, heightInMeters);
// static container body, with the collisions at screen borders
b2BodyDef screenBorderDef;
screenBorderDef.position.Set(0, 0);
b2Body* screenBorderBody = world->CreateBody(&screenBorderDef);
b2EdgeShape screenBorderShape;
// Create fixtures for the four borders (the border shape is re-used)
screenBorderShape.Set(lowerLeftCorner, lowerRightCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(lowerRightCorner, upperRightCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperRightCorner, upperLeftCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperLeftCorner, lowerLeftCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
注意:此代碼適用於Box2D v2.2.1。我假設你正在使用的是因爲你說過「以前的版本」,它需要以不同的方式編寫代碼(使用SetAsEdge方法)。
謝謝,工作很棒:) ......只有一個問題,爲什麼人們以米爲單位獲得寬度?我看到有幾個人在做這個...... –
Box2D標準長度單位是米,雖然在你的應用程序中「長」米是如何定義的。因此PTM(像素到米)的比例。 – LearnCocos2D
ahhh非常感謝,這有助於... –