Simulate “Newton's law of universal gravitation” using Box2D

吃可爱长大的小学妹 提交于 2019-11-30 12:16:13

问题


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



来源:https://stackoverflow.com/questions/6758060/simulate-newtons-law-of-universal-gravitation-using-box2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!