模拟“牛顿万有引力定律".使用Box2D [英] Simulate "Newton's law of universal gravitation" using Box2D

查看:84
本文介绍了模拟“牛顿万有引力定律".使用Box2D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Box2D模拟牛顿万有引力定律.

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.

有什么提示吗?

推荐答案

这很容易实现:

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 );
    }
}

这篇关于模拟“牛顿万有引力定律".使用Box2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆