Hello FreeTom.
Just get the 'vector' between the two centers of mass:
Code: Select all
vx = star.position.x - planet.position.x
vy = star.position.y - planet.position.y
You now have a vector pointing from the planet to the star.
Negate vx, yv if you want to rotate the vector 180 degrees.
Once you know the vector between the two objects, you can gen the distance:
Code: Select all
dist = math.sqrt(vx^2 + vy^2)
-- or --
dist = math.sqrt(vx*vx + vy*vy)
The force of gravity is inversely proportional to the distance:
Code: Select all
force = (G*planetMass*starMass)/dist^2
We already know these variables except for G which is the gravitational constant.
If you assume that G = 6.673 x 10^-11 N m^2/kg^2
then make sure "dist" is in meters and "mass" is in kg.
So far so good, all we have to do is apply the force to both objects.
The next formula to remember is:
Code: Select all
force = mass*acceleration
-- so --
acceleration1 = force/planetMass
acceleration2 = force/starMass
You now know the acceleration of the two objects.
Note:Acceleration is the change in velocity per 1 second.
Once you know the acceleration caused by gravity,
you have to apply it along the axis of the vector vx, vy.
First, normalize vx, vy:
Code: Select all
nx, ny = 0, 0
if dist > 0 then
nx, ny = vx/dist, vy/dist
end
Next, multiply the normalized vector by the acceleration:
Code: Select all
acceleration1x = nx*acceleration1
acceleration1y = ny*acceleration1
This is your change in velocity
per second.
So we have to multiply by "delta" for each step.
Last step:
add the change in velocity (acceleration*dt) to the current velocity of each object.
Code: Select all
planet.velocity.x = planet.velocity.x + acceleration1x*dt
planet.velocity.y = planet.velocity.y + acceleration1y*dt
Keep in mind that the two objects will move at different velocities
since the more massive object will be slower to accelerate.
TL;DR
Just get the vector between the two objects, normalize it
and multiply by the force of attraction.