我试图弄清楚如何在我正在创建的应用程序中实现重力。我在 Opengl 中有一个球体,我想给它像行星一样的重力。所以它附近的任何小物体都会“掉”到它的表面。
我想知道是否有人可以指出我的 C++ 示例的方向。
Maybe it is too late for this, but at least others might get something from this.
Here is a program I just wrote in C++ and OpenGL of gravity simulation. Hope it will help. The source code is in the description of the video and can be found here as well.
http://www.youtube.com/watch?v=TXY6NJm5se0&list=UU0OHvV8fkDcKlWAm1vFqc1w&index=1&feature=plcp
您需要编写一个实现重力公式的函数,例如:
const float g = 9.81f; // Gravity of Earth in m/s²
float gravity(Vec3 p1_pos, Vec3 p2_pos, float p1_mass, float p2_mass)
{
float distance = (p2_pos - p1_pos).length();
return g * p1_mass * p1_mass / (distance*distance);
}
将力的大小乘以平行于 top2_pos - p1_pos 的单位向量,以给出力的方向。然后,只需使用 F = ma 计算对象上的加速度
struct object
{
Vec3 pos;
Vec3 vel;
float mass;
void add_force(Vec3 force);
};
void object::add_force(Vec3 force, float dt)
{
vel += (force / mass) * dt;
}
请务必将加速度乘以 dt,即每帧的秒数。这允许您的模拟以常规速度进行,而不管计算机的速度如何。我编写了一个 NBody 模拟,它使用与上述技术非常相似的技术来模拟任意数量的行星并计算它们相互吸引的力。对于您要模拟的每个对象,使用重力函数来获取力的大小并在对象上调用 add_force() 来推动它。您需要将 Vec3 替换为您自己的向量类,并确保它具有运算符重载。OpenGL 可能提供了一个。
I think there is a mistake. The formula that calculates the force between object A of mass mA and object B of mass mB at distance r is: [g * (mA * mB)] / (r^2)
Same as above until now. The mistake is that when using meters for distances and kg for mass there is a constant that makes the force porportional with the measurments in real world. That constant is in my fomula noted as 'g'. This 'g' is not 9.81 . This 'g', the gravitational constant. is equal with: 6.67300 × 10^-11 m^3 / (kg * s^2) .
So, for objects A and B both having masses of 1 kg, and the distance 'r' being 1 meter the force between them will be: 6.67300 × 10^-11 (kg * m) / (s^2) , or 6.67300 × 10^-11 Newtons . This is a very small force :) Our planet hass mA HUGE :D . This mass is what gives at the surface a force of 9.81 Newtons on a body with mass of 1 kg.