private void UpdateGravity(GameTime gameTime)
{
for (int i = 0; i < worldObjects.Length; i++)
{
if (worldObjects[i] is Planet || worldObjects[i] is Spaceship)
{
for (int j = 0; j < worldObjects.Length; j++)
{
/*
* physics annotation:
* m: meter
* s: seconds
* kg: kilogram
*
* F: gravitational force in Newton = kg * m / s^2
* G: gravitational constant in m^3 / kg / s^2
* mass1: mass of the first object in kg
* mass2: mass of the second object in kg
* a : acceleration in m / s^2
* r: distance vector between the two objects
* v: velocity vector
* t: time in seconds
*
* F = G * mass1 * mass2 / r^2
* F = a * mass2 => a = F / mass2 = G * mass1 / r^2
* v = a * t in m / s
*/
// planets should not be influenced by gravity if they are not set to flexible
if (!(worldObjects[j] is Planet && (worldObjects[j] as Planet).IsFlexible == false))
{
Vector2 distance = new Vector2(worldObjects[i].Position.X - worldObjects[j].Position.X, worldObjects[i].Position.Y - worldObjects[j].Position.Y);
// avoid dividing by zero(meaning the two objects are either the same or already collided)
if (distance.Length() != 0)
{
float acceleration = ((float)(GameAssets.G * worldObjects[i].Mass / distance.LengthSquared()));
distance.Normalize();
Vector2 accelerationVector = Vector2.Multiply(distance, acceleration);
Vector2 velocityVector = Vector2.Multiply(accelerationVector, 0.01f * (float)gameTime.ElapsedGameTime.TotalSeconds);
worldObjects[j].Velocity += Vector2.Divide(velocityVector, GameAssets.N * difficulty);
}
}
}
}
}
}