Reputation: 720
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.
Upvotes: 3
Views: 2183
Reputation: 308733
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.
Upvotes: 3
Reputation: 1720
Assuming that you've got an in-game quantized unit of time, a "tick" of the clock, if you will, give each body a velocity vector (how much, and in which directions, it moves per "tick") and for each tick, have each other body change its velocity vector by some amount based on their distance (exert a force on it, divided by its mass). Then, whenever your clock ticks, the bodies move according to their velocity vectors, and then their velocity vectors changed based on the net force on them. As long as you decide which happens first - acceleration or motion - provided that your ticks are small enough, you should be fine.
Upvotes: 1