I have the following code in my collision test:
if (Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2) <= Math.pow(A.radius + B.radius, 2)) {
A.x_vel = (A.x_vel * (A.mass - B.mass) + (2 * B.mass * B.x_vel)) / (A.mass + B.mass);
A.y_vel = (A.y_vel * (A.mass - B.mass) + (2 * B.mass * B.y_vel)) / (A.mass + B.mass);
B.x_vel = (B.x_vel * (B.mass - A.mass) + (2 * A.mass * A.x_vel)) / (A.mass + B.mass);
B.y_vel = (B.y_vel * (B.mass - A.mass) + (2 * A.mass * A.y_vel)) / (A.mass + B.mass);
A.x = A.x + A.x_vel;
A.y = A.y + A.y_vel;
B.x = B.x + B.x_vel;
B.y = B.y + B.y_vel;
}
The result is the circles sticking together. How can I solve this? Demo at http://jsfiddle.net/tLpEV/3/ (full screen: http://fiddle.jshell.net/tLpEV/3/show/)
You are changing the velocity for A first, then you use the changed velocity to calculate the new velocity for B. You need to use the original velocity of A, so store the new velocity for A in temporary variables until you have calculated the velocity for B:
Demo: http://jsfiddle.net/Guffa/tLpEV/4/