Search code examples
objective-cxcodecocos2d-iphonebox2dbox2d-iphone

Box2D world size


I have created a box2d world, and I wanted to limit the height of the world. I did search google and apparently there was an option in the previous version of box2d where you would have to define the size of your world, but I am not sure if you were able set the height of the world but in the current version they have taken that option completely off.

So I am just looking for a way to limit the height, as my player is a ball that jumps up and down and I want to limit how high it can jump (the jumps are done by physics and gravity and the speed of the ball so after a few good jumps, the ball jumps really high as its speed increases and I dont want to limit the speed) and put border on let say y=900.


Solution

  • The Box2D world has an infinite size. You can't limit the world, but you can create a shape that encloses a certain area in the Box2D world.

    Here's how to create a body and shape that puts a shape just around the screen, so that objects don't leave the screen. It is easy to adapt this code by changing the corner coordinates to fit whatever you need:

            // 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);
    

    Note: this code is for Box2D v2.2.1. I assume that's what you're using because you said "previous version" which required this code to be written differently (with the SetAsEdge method).