[英]How to apply 2D gravitational effects to sprites
在2D无限空间内,我有两个圆形的精灵,它们代表外太空中的大量物体。
每个物体都有一对x
, y
坐标, mass
, speed
和direction
(以弧度为单位)。
在动画的每一帧上,我为每个主体运行以下代码(其中this
是要更新的主体, other
是另一个主体):
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.speed
和this.direction
以模拟重力。
作用在给定物体上的重力表示为矢量,并利用分量( ax
和ay
)产生加速度,这些分量的计算(基于您已有的)如下:
squared_distance = square(x) + square(y)
distance = sqrt(squared_distance)
accel = other.mass / squared_distance
ax = accel * x / distance
ay = accel * y / distance
请注意,不需要angle
(力/加速度方向)。
每个物体都应具有关联的速度(而不是speed
),该speed
应该是两个分量的向量( vx
和vy
)。 像这样更新(其中dt
是两次更新之间的时间间隔):
this.vx += ax * dt
this.vy += ay * dt
给定物体的速度更新后,就可以像这样重新定位(更新其x
, y
坐标):
this.x += this.vx * dt
this.y += this.vy * dt
您可以根据需要计算速度和方向,但此处不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.