我正在做一个太阳系模拟,我有所有的初始值,图纸似乎没问题,但是,他们不动

问题描述 投票:0回答:2

这是我的 love.update(dt) 函数,我认为问题在于:

    function love.update(dt)
local  G = 6.67430e-11 -- gravitational constant
-- Force Between all the bodies 
for i, body in ipairs(bodies) do
 local fx = 0
  local fy = 0

 for j, body in ipairs(bodies) do
  if i ~= j then // skip calculation for the same body
            local dx = body.px - body.x
            local dy = body.py - body.y
            local dist = math.sqrt(dx^2 + dy^2)
            local f = G * body.mass * body.mass / dist^2
        
        theta = math.atan2(dy, dx)
            fx = math.cos(theta) * f
            fy = math.sin(theta) * f
    return fx, fy
  end
   end
        
  body.ax = fx / body.mass
  body.ay = fy / body.mass

--Update of Velocity and Position
     for _, body in ipairs(bodies) do
    body.x = body.x + body.vx * dt + 0.5 * body.ax * dt^2
    body.y = body.y + body.vy * dt + 0.5 * body.ay * dt^2
    body.vx = body.vx + 0.5 * (body.ax + body.a0x) * dt
    body.vy = body.vy + 0.5 * (body.ay + body.a0y) * dt
    body.a0x = body.ax
    body.a0y = body.ay
end
end

我相信问题可能出在 for 循环中。

我用 px 计算了 dx 的实数值以获得 f 的实数值。获得 f 的值后,我可以计算 fx 和 fy,从而计算出 ax 和 ay 的值。之后我可以更新每个对象的速度和位置。 这是初始值的一个例子:

   bodies[1] = {name = "sun", mass = 1.9891e30, radius = 696340000, x = width/2, y = height/2, vx = 0, vy = 0 , a0x= 0, a0y= 0, ax= 0, ay= 0}
   bodies[2]= {name = "mercury", mass = 0.3302e24, radius = 2440000, x = width/2 + 0.38*100, y =  height/2, vx = 0, vy = 48.92 * 1000, a0x= 0, a0y= 0, ax= 0, ay= 0, px = 46.0e9, py = 0} 

我试过:

local dx = body.px - body.x
local dx = body2.px - body1.px
local dx = body.px - body.px

我计算 dx 和 dy 是为了找到两个物体在 x 和 y 方向上的距离。 在模拟重力的情况下,我们需要知道每对物体之间的距离才能计算它们之间的力。

lua simulation physics modeling love2d
2个回答
0
投票

您应该将嵌套循环中的变量名称更改为不同的名称,例如

other_body
,使用相同的名称可能会导致它被覆盖并造成混淆。


0
投票

为什么你更新到一半有退货?在做任何有趣的事情之前,这基本上会杀死你的更新。您可能想使用

break
.

我假设您想将这些 fx/fy 应用于身体。所以我认为斧头线也应该在循环中。

请格式化代码,它有助于了解发生了什么。

© www.soinside.com 2019 - 2024. All rights reserved.