I am trying to write a simple physical simulation in which balls with varying radii and masses bounce in a completely elastic and frictionless environment. I wrote my own code following this resource: http://www.vobarian.com/collisions/2dcollisions2.pdf , and I also checked the code here: Ball to Ball Collision - detection and processing
QUESTION EDITED
With the help of Rick Goldstein and Ralph, I got my code for work (there was a typo ..). Thank you for help. However, I'm still confused about why another algorithm is not working for me. The balls bounce in the right direction, but the full energy of the system is never conserved. Speeds are getting faster and faster until the balls begin to flash in static positions on the screen. I really want to use this code in my program because it is much more concise than the one I wrote.
Here is a functional algorithm that I wrote (although I took the first bit from this other source). Its in the Bubble class:
public void resolveCollision(Bubble b) {
And here is one that doesn't work
public void resolveCollision(Bubble b) { // get the minimum translation distance Vector2 delta = (position.subtract(b.position)); float d = delta.getMagnitude(); // minimum translation distance to push balls apart after intersecting Vector2 mtd = delta.multiply(((getRadius() + b.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / b.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); b.position = b.position.subtract(mtd.multiply(im2 / (im1 + im2))); // impact speed Vector2 v = (this.velocity.subtract(b.velocity)); float vn = v.dot(mtd.normalize()); // sphere intersecting but moving away from each other already if (vn > 0.0f) return; // collision impulse (1f is the coefficient of restitution) float i = (-(1.0f + 1f) * vn) / (im1 + im2); Vector2 impulse = mtd.multiply(i); // change in momentum this.velocity = this.velocity.add(impulse.multiply(im1)); b.velocity = b.velocity.subtract(impulse.multiply(im2)); }
Let me know if you find anything. Thanks
source share