如何将 2D 重力效果应用于精灵

How to apply 2D gravitational effects to sprites

在 2D 无限 space 中,我有两个圆形精灵代表外部 space 中的大质量物体。

每个body都有一对xy坐标、一个mass、一个speed和一个direction(在弧度)。

在每一帧动画中,我 运行 每个 body 的以下代码(其中 this 是正在更新的 body,other 是另一个 body):

x, y = other.x - this.x, other.y - this.y

angle = atan2(y, x)
distance = root(square(x) + square(y))
force = this.mass * other.mass / square(distance)

注意:我忽略了 G,因为它只是一个乘数。

我知道如何根据坐标、速度和方向移动物体,但不知道如何更新 this.speedthis.direction 来模拟重力。

作用在给定物体上的重力表示为一个矢量,并产生具有分量(axay)的加速度,这些分量是这样计算的(基于你已有的) :

squared_distance = square(x) + square(y)
distance = sqrt(squared_distance)

accel = other.mass / squared_distance    
ax = accel * x / distance 
ay = accel * y / distance

注意angle(force/acceleration方向)不需要。

每个物体都应该有一个关联的速度(而不是 speed),它应该是一个双分量向量(vxvy)。它是这样更新的(其中 dt 是更新之间的时间间隔):

this.vx += ax * dt
this.vy += ay * dt

一旦更新了给定物体的速度,就可以重新定位它(更新其 xy 坐标),如下所示:

this.x += this.vx * dt
this.y += this.vy * dt

需要速度和方向的可以计算,这里不需要。