HuRriC4nE
11th June 2009 14:14 UTC
need coding help ... i'm stuck here
Hello everybody,
I'd like to make a preset with "objects" (planets, whatever)
in an gravitationpotential.
the differential equations for a masspoint is (2dimensional)
x''(t) + (G*M/r^3)*x(t) == 0;
y''(t) + (G*M/r^3)*x(t) == 0;
r == sqrt(x^2 + y^2)
_________________________
This differential equation(s)
must be calculated numerical - that is just the way avs is calculating - from frame to frame.
so i thought:
xx - x-position
yy - y-position
vx - x-velocity
vy - y-velocity
_________________
//frame
rr = sqrt(xx^2 + yy^2)
R = 1/rr;
vx = vx - xx/(R^3)*stepsize
vy = vy - yy/(R^3)*stepsize
xx = xx + vx
yy = yy + vy
//render
x = xx
y = yy
why does this not work???
jheriko
26th June 2009 13:44 UTC
I did point gravity in one of my j10 presets... that might help. I think its the first one... can't remeber the name (Physics or something totally uninspired).
Rather than messing with potentials etc the best way (imo) is to model the acceleration due to gravity by combining newton's gravity with his second law:
f = G m_1 m_2 / r^2 and f = m a
If we call m_1 the "free" mass in the field of a "static" m_2 and consider m_2 to be static then we can take the distance from m_1 to m_2 to get r and get the acceleration as G m_2 / r^2. You can then use Euler steps, Verlet, RK4 or whatever to move m_1 and update its position/velocity. Euler steps are usually sufficient and look like this (assuming we fill out G m_2 and r, and s is the position of m_1):
a = G * m_2 / sqr(r);
v = v + a * dt;
s = s + v * dt;
This is a simplified case. If you want multiple objects to gravitate with each other properly then you will have to work out the changes in velocity for and from all of the particles first, then apply their sum to update the positions, otherwise the changes in positions will corrupt the accelerations/velocities generated for the next particle once applied. If you have a bunch of particles with equal mass, whichever one comes first in the loop will seem to drag the others around with it...
so, for a bunch of gravitating particles the algorithm is then:
loop across all particles (p_i):
initialise velocity sum for p_i to zero
loop across all particles (p_j):
work out acceleration due to gravity on p_i from p_j
work out resultant velocity change (a * dt, from v = v + a * dt)
add this change to the velocity sum for p_i
repeat
repeat
loop across all particles (p_i):
add velocity sum for p_i to p_i's velocity
update position using s = s + v * dt
repeat
iirc this should work whilst avoiding most of the major pitfalls.
btw, use inverse square root (invsqrt) its faster and probably has around a 0.1% error at worst. i wrote an article on that a while ago you may or may not like to read...
http://jheriko-rtw.blogspot.com/2009...ving-fast.html