Search code examples
pythonphysicsgame-physics

Newtonian gravity simulation


I'm writing a 2D game in Python that has gravity as a major mechanic.

I have some of the game engine made, but the part where I'm stuck is actually determining what to add to the X and Y velocities of each mass.

So say I have circle A and circle B, each with a position, a velocity, and a mass. Each should be pulled towards the other fairly realistically, simulating Newtonian gravity. How would I achieve this?

Yes, I am being very ambiguous with the units of measurement. Later I can experiment with changing the variables to fit the formula.


Solution

  • You need to solve the equations of motion for each body. They'll be written as a set of coupled, first-order, ordinary differential equations. You'll write one equation each for the x- and y-directions, which will give you the acceleration as a function of the gravitational force between the two bodies divided by their respective masses.

    You know the relationships between acceleration, velocity, and displacement.

    You end up four coupled ordinary differential equations to solve. Use a time stepping solution to advance the solution in time - explicit or implicit, your choice.