box2d教程讲解的很详细,不做赘余
#define DEGTORAD 0.0174532925199432957f class FooTest : public Test{ public: FooTest() { //创建物体 b2BodyDef myBodyDef; myBodyDef.type = b2_dynamicBody;//物体类型,3种,如下 myBodyDef.position.Set(0,20);//位置 myBodyDef.angle = 0;//角度 //create dynamicBody = m_world->CreateBody(&myBodyDef); b2PolygonShape boxShape; boxShape.SetAsBox(1,1);//物体大小 //动态物体 b2FixtureDef boxFixtureDef; boxFixtureDef.shape = &boxShape; boxFixtureDef.density = 1; dynamicBody->CreateFixture(&boxFixtureDef);//定制器 dynamicBody->SetTransform(b2Vec2(10, 20), 45*DEGTORAD);//角度 dynamicBody->SetLinearVelocity(b2Vec2(-5, 5));//线速度 dynamicBody->SetAngularVelocity(-90*DEGTORAD);//角速度 //静态物体 myBodyDef.type = b2_staticBody; myBodyDef.position.Set(0, 10); staticBody = m_world->CreateBody(&myBodyDef); staticBody->CreateFixture(&boxFixtureDef); //动力学物体 myBodyDef.type = b2_kinematicBody; myBodyDef.position.Set(-18, 11); kinermaticBody = m_world->CreateBody(&myBodyDef); kinermaticBody->CreateFixture(&boxFixtureDef); kinermaticBody->SetLinearVelocity(b2Vec2(1, 0)); kinermaticBody->SetAngularVelocity(360*DEGTORAD); //dynamicBody = kinermaticBody; } //do nothing, no scene yet void Step(Settings* settings){ //run the default physics and rendering Test::Step(settings); //show some text in the main screen m_debugDraw.DrawString(5, m_textLine, "Now we have a foo test"); m_textLine += 15; if(dynamicBody){ b2Vec2 pos = dynamicBody->GetPosition(); float angle = dynamicBody->GetAngle(); b2Vec2 ve1 = dynamicBody->GetLinearVelocity(); float angularve1 = dynamicBody->GetAngularVelocity(); m_debugDraw.DrawString(5, m_textLine, "Position: %.3f, %.3f Angle: %.3f", pos.x, pos.y, angle * DEGTORAD); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "velocity: %.3f, %.3f velocity: %.3f", ve1.x, ve1.y, angularve1 * DEGTORAD); m_textLine += 15; if(pos.y <= 10){ m_world->DestroyBody(dynamicBody); dynamicBody = NULL; } } } static Test* Create(){ return new FooTest; } b2Body* dynamicBody; b2Body* staticBody; b2Body* kinermaticBody; };