//class member variable to keep track of three bodiesb2Body*bodies[3];FooTest(){//body definitionb2BodyDefmyBodyDef;myBodyDef.type=b2_dynamicBody;//shape definitionb2PolygonShapepolygonShape;polygonShape.SetAsBox(1,1);//a 2x2 rectangle//fixture definitionb2FixtureDefmyFixtureDef;myFixtureDef.shape=&polygonShape;myFixtureDef.density=1;//create identical bodies in different positionsfor(inti=0;i<3;i++){myBodyDef.position.Set(-10+i*10,20);bodies[i]=m_world->CreateBody(&myBodyDef);bodies[i]->CreateFixture(&myFixtureDef);}//a static floor to drop things onmyBodyDef.type=b2_staticBody;myBodyDef.position.Set(0,0);polygonShape.SetAsEdge(b2Vec2(-15,0),b2Vec2(15,0));m_world->CreateBody(&myBodyDef)->CreateFixture(&myFixtureDef);}
//in the Step() function//cancel gravity for body 1 onlybodies[1]->ApplyForce(bodies[1]->GetMass()*-m_world->GetGravity(),bodies[1]->GetWorldCenter());
声明:本教程翻译自:Box2D C++ tutorials-Custom gravity,仅供学习参考。为每一个物体指定不同的重力我们经常会遇到的一个问题是,在其他物体依然遵循重力规则的情况下,如何让指定的物体不受重力影响。其实这实现起来很简单,现在就用我们所了解的力矩试着实现它。我们还是以上一个话题的场景为基础,使用三个独立的物体。123