Simulate “Newton's law of universal gravitatio

2019-02-02 00:45发布

问题:

I want to simulate Newton's law of universal gravitation using Box2D.

I went through the manual but couldn't find a way to do this.

Basically what I want to do is place several objects in space (zero gravity) and simulate the movement.

Any tips?

回答1:

It's pretty easy to implement:

for ( int i = 0; i < numBodies; i++ ) {

    b2Body* bi = bodies[i];
    b2Vec2 pi = bi->GetWorldCenter();
    float mi = bi->GetMass();

    for ( int k = i; k < numBodies; k++ ) {

        b2Body* bk = bodies[k];
        b2Vec2 pk = bk->GetWorldCenter();
        float mk = bk->GetMass();

        b2Vec2 delta = pk - pi;
        float r = delta.Length();
        float force = G * mi * mk / (r*r);

        delta.Normalize();
        bi->ApplyForce(  force * delta, pi );
        bk->ApplyForce( -force * delta, pk );
    }
}


回答2:

Unfortunately, Box2D doesn't have native support for it, but you can implement it yourself: Box2D and radial gravity code