I have a simple code that calculates the acceleration of a body every update of my simulation using the Newton's law of universal gravitation and the second law of motion.
def move_bodies():
def get_dist(b1, b2):
return math.hypot(b2['x'] - b1['x'], b2['y'] - b1['y'])
for body in bodies:
acceleration = 0
angle = 0
for other_body in bodies:
dist = get_dist(body, other_body)
if body != other_body:
angle = math.atan2(other_body['y'] - body['y'], other_body['x'] - body['x'])
acceleration = (GRAVITY_CONSTANT * body['m'] * other_body['m'] / dist ** 2) / body['m']
body['x'] += math.cos(angle) * body['vx']
body['vx'] += acceleration
body['y'] += math.sin(angle) * body['vy']
body['vy'] += acceleration
when these bodies interact, something unexpected happens when their x/y values are approaching one another -- the bodies move at extremely high speeds and seemingly disappear off the screen.
For example, if we have a body at (200, 100) and another at (200, 300), they do not gravitate towards one another as they would do in a situation where they have unique (x, y) values such as (200, 100) and (300, 400).
Looking at the code, as the y-values of body
and other_body
approach one another, values get exceedingly large(?)
I can't quite pin down the issue as I'm a beginner. Any suggestions/criticism?