To use box2d, you must first create a world. Only when you have a world can you simulate everything in box2d.
Create world:
B2vec2 gravity (0.0f,-10.0f );
World= New b2world (gravity );
Bool dosleep = true;
World-> Setallowsleeping (dosleep );
World-> Setcontinuousphysics (true );
Second, there must be a boundary for simulating the physical world. box2d will simulate the area inside the boundary, and the rigid body (or genie) running out of the boundary will be frozen and the simulation will be stopped. Therefore, the size of the boundary is larger than that of the window, which is suitable for better simulation results and performance.
Set boundaries:
B2bodydef groundbodydef;
Groundbodydef. position. setzero ();
B2body *Groundbody= World-> createbody (& groundbodydef );
B2edgeshape
Groundbox;
Groundbox. Set (b2vec2 (0, 0), b2vec2 (winsize. width/ptm_ratio, 0 ));
Groundbody-> Createfixture (&Groundbox, 0 );
Groundbox. Set (b2vec2 (0, 0), b2vec2 (0, winsize. Height/ptm_ratio ));
Groundbody-> Createfixture (&Groundbox, 0 );
Groundbox. Set (b2vec2 (0, winsize. Height/ptm_ratio), b2vec2 (winsize. width/ptm_ratio, winsize. Height/ptm_ratio ));
Groundbody-> Createfixture (&Groundbox, 0 );
Groundbox. Set (b2vec2 (winsize. width/ptm_ratio, winsize. Height/ptm_ratio), b2vec2 (winsize. width/ptm_ratio, 0 ));
Groundbody-> Createfixture (&Groundbox, 0 );
Bind the genie to a rigid body in box2d, And the genie will constantly update the position and effect with the simulation of box2d.
Implement wizard binding:
B2bodydef
Bodydef;
Bodydef. Type = b2_dynamicbody;
Bodydef. Position. Set (point. X/ptm_ratio, point. Y/ptm_ratio );
Bodydef. Userdata =Psprite;
B2body *Body= World-> createbody (&Bodydef);
B2polygonshapeShapebox;
Shapebox. Setasbox (. 5f,. 5f );
B2fixturedefFixturedef;
Fixturedef. Shape = &Shapebox;
Fixturedef. Density = 1.0f; // density Coefficient
Fixturedef. Friction = 0.3f; // Friction Coefficient
Body-> Createfixture (&Fixturedef);
Finally, it implements Physical Simulation and updates the location or effect of the genie.
Void Update (float DT)
{
World-> step (DT, 8, 1 );
For (b2body * B = World-> getbodylist (); B; B = B-> getnext ())
{
If (B-> getuserdata ()! = NULL)
{
Ccsprite * sprite = (ccsprite *) B-> getuserdata ();
Sprite->Setposition(CCP (B-> getposition (). x * ptm_ratio, B-> getposition (). y * ptm_ratio ));
Sprite->Setrotation(-1) * cc_radians_to_degrees (B-> getangle ()));
}
}
}
reference blog (http://blog.csdn.net/cq361106306/article/details/7933128)