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メソッドを使って)別々に書かなければならなかった "以前のバージョン"と言っていたので、あなたが使っているものだと思います。
ありがとう、素晴らしい作品:) ... 1つの質問、なぜ人々はメートルで幅を取得するのですか?私はいくつかの人々がこれを行うのを見ました... –
Box2Dの標準長さの単位はメートルですが、あなたのアプリにどれくらい長さがあるのかは誰でも定義できます。従って、PTM(画素対メーター)比。 – LearnCocos2D
あああ、ありがとう、ありがとうございます... –