Game Development Reference
In-Depth Information
World setup, check. What next? Well, you should limit the movement of the Box2D
bodies to within the visible screen area. For that, you'll need a static body. The
simplest way to create a static body is by using the world's CreateBody method and
then adding fixtures (collision information) to it. I'll repeat the relevant code from List-
ing 12-3 here:
// Define the ground body.
b2BodyDef groundBodyDef;
b2Body* groundBody = world-> CreateBody(&groundBodyDef);
Bodies are always created through the world's CreateBody method. This ensures
that the body's memory is correctly allocated and freed. The b2BodyDef is a struct
that holds all the data needed to create a body, such as position and the body type. By
default, an empty body definition creates a static body at position 0, 0.
Note The &groundBodyDef variable is passed with a leading & (ampersand)
character to the CreateBody method. That's C++ for “Give me the memory
address of groundBodyDef .” If you look at the definition of the
CreateBody method, it requires a pointer passed to it:
b2World::CreateBody(const b2BodyDef *def); . Because point-
ers store a memory address, you can get that address of a nonpointer variable by
prefixing it with the ampersand character.
The body itself doesn't do anything. To make it enclose the screen area, you have to
create a shape with four sides:
// Define the ground box shape.
CGSize screenSize = [CCDirector sharedDirector].winSize;
float boxWidth = screenSize.width / PTM_RATIO;
float boxHeight = screenSize.height / PTM_RATIO;
b2EdgeShape groundBox;
int density = 0;
// bottom
groundBox.Set(b2Vec2(0, 0), b2Vec2(boxWidth, 0));
groundBody-> CreateFixture(&groundBox, density);
// top
Search Nedrilad ::




Custom Search