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 メソッドを使用して)別の方法で記述する必要がある「以前のバージョン」と言ったので、それを使用していると思います。