Search code examples
javacollision-detectionphysicscollisiongame-physics

How to fix circles overlap in collision response?


Since in the digital world a real collision almost never happens, we will always have a situation where the "colliding" balls overlap.

How to put back balls in situation where they collide perfectly without overlap?

I would solve this problem with a posteriori approach (in two dimensions).

In short I have to solve this equation for t:

((x2 - t * v.x2) - (x1 - t * v.x1))^2 + ((y2 - t * v.y2) - (y1 - t * v.y1))^2 = (r1 + r2)^2

Where:

  • t is a number that answers to the question: how many frames ago did the collision happen perfectly?
  • (x1, y1) is the center of the first ball
  • (x2, y2) is the center of the second ball
  • (v.x1, v.y1) and (v.x2, v.y2) are their velocities.

but the solution from WolframAlpha is too complicated (I changed the name of the velocities but essentially does not change anything).


Solution

  • It looks complicated because it's the full solution, not just the simplified polynomial form of it. Multiply everything out and gather the constant, t, and t^2 terms, and you'll find that it becomes just at^2 + bt + c = 0. From there you can just use the quadratic formula.

    Also, if you want to keep things simple, do them with vector math. There's no reason here to separate out the x and y coordinates; vector addition and dot products are all you need.

    Finally, all that matters is the relative position and relative velocity. Pretend one circle is at the origin and stationary, and apply the difference to the other ball. That doesn't change the answer, but it does reduce the number of variables you're wrangling.