1

I made a simulation that calculates the elastic collision and gravity between planets.
It was fine at first, but as we go on, the symmetry breaks down at some point. Here is the Video (break at 1:40)
I tried with a lot of codes, but the symmetry eventually breaked.

Here is elastic collision code:

@staticmethod
def reflect_colliding_circles(a, b):
    delta = vector(a.rect.center[0], a.rect.center[1]) - vector(b.rect.center[0], b.rect.center[1])
    d = delta.length()
    mtd = delta * ((a.radius+b.radius)-d)/d

    im1 = 1 / a.m
    im2 = 1 / b.m

    a.pos += mtd * (im1 / (im1 + im2))
    b.pos -= mtd * (im2 / (im1 + im2))

    v = a.vel - b.vel
    vn = v.dot(mtd.normalize())
    if vn > 0.0:
        return

    i = (-1 * (1.0 + E) * vn) / (im1 + im2)
    impulse = mtd.normalize() * i

    a.vel += impulse * im1
    b.vel -= impulse * im2

And Here is gravity code:

def calc_gravity(self, otpl):
    force = self.pos - otpl.pos
    if force == vector(0, 0):
        return vector(0, 0)
    distance = force.magnitude()
    force = force.normalize()
    strength = -(G * self.m * otpl.m) / (distance ** 2)
    force = force * strength
    return force

The Full code is here
Why it happen and how to fix it?
I think maybe it is float's accuracy error, It's just my guess..
Thanks!
(Sorry for my poor English, I used translator a little bit..)

World
  • 21
  • 3
  • To me it looks like they are hitting the side of the screen. Can you try to disable collision with the screen boundaries and see if the problem goes away? – MegaIng Jul 14 '21 at 14:32
  • Still no problem solved.. – World Jul 15 '21 at 00:22
  • Btw, you do have a decent amount of logic errors in your code that prevent it from being a true gravity simulation (e.g. it should be `vel += dt*acc`, `pos += dt*vel` and you should take a look at [fixing your timing](https://stackoverflow.com/questions/13591949/in-pygame-normalizing-game-speed-across-different-fps-values/13592134). But I am not sure if those are actually the reason for this bug. – MegaIng Jul 15 '21 at 01:18
  • But I am not sure if there is anything you can do to actually fix this: This is a chaotic system, and any small error might lead to any arbitrary large error later on. That little asymmetry might already happen early on on some call to `.normalize`, caused by floating point arithmetic. – MegaIng Jul 15 '21 at 01:23
  • I used delta time. But if there is a delay, it will pass through the planet it supposed to collision. – World Jul 15 '21 at 01:24

0 Answers0