Gravity
This is the initial version of a 2d-space gravity tech demo. Might become a SpaceWar clone, might become something else.
The thing that makes it work is this interpretation of Newton's Law of Gravity (F = G*(M1*M2)/D^2)
def calc_gravity (m1, m2) G = 0.05 dx = m2.x - m1.x dy = m2.y - m1.y d2 = dx**2 + dy**2 d = Math.sqrt(d2) f = G * (m1.m * m2.m) / d2 fx = f * (dx/d) fy = f * (dy/d) return fx, fy end
We start with a universal constant for gravity (G) that's somewhat stronger than in the real world
Then we need to find the distance between our first object (the ship) and the second (the star). We find both the X and Y position differences, then use Pythagorean's Theorem to give us the distance. We stave all 4 values (Dx, Dy, D-Squared, and D) because we'll use them in different parts of the equation
Next we calculate the gravitational force. For this we need our distance-squared (d2) value since that's what Newton's formula calls for.
Once we have the total force, we can get the force in the X axis and force in the Y axis by taking our total force and multiplying it by the ratio of our distance-in-this-axis by total-distance.
Then re just return our 2 forces. Strictly speaking, it may make sense to apply them to the object at this time, but we'll do that in another place for now just in case gravitational forces come in handy later.
Files
Get Gravity Experiments
Gravity Experiments
Playing with gravity in 2d space
Status | In development |
Author | Kehvarl |
More posts
- Thrust2 hours ago
Leave a comment
Log in with itch.io to leave a comment.