簡體   English   中英

如何將2D重力效應應用於精靈

[英]How to apply 2D gravitational effects to sprites

在2D無限空間內,我有兩個圓形的精靈,它們代表外太空中的大量物體。

每個物體都有一對xy坐標, massspeeddirection (以弧度為單位)。

在動畫的每一幀上,我為每個主體運行以下代碼(其中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.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 (力/加速度方向)。

每個物體都應具有關聯的速度(而不是speed ),該speed應該是兩個分量的向量( vxvy )。 像這樣更新(其中dt是兩次更新之間的時間間隔):

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

給定物體的速度更新后,就可以像這樣重新定位(更新其xy坐標):

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

您可以根據需要計算速度和方向,但此處不需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM