I am making a game in HTML5, Canvas, and this is my code for resolving collision between two moving circles:
function resCCCol(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = dx * dx + dy * dy;
var vx = b.vx - a.vx;
var vy = b.vy - a.vy;
var dot = dx * vx + dy * vy;
if (dot > 0) {
var scale = dot / dist;
var cx = dx * scale;
var cy = dy * scale;
var mass = a.r + b.r;
var cw1 = 2 * b.r / mass;
var cw2 = 2 * a.r / mass;
a.vx += cw1 * cx
a.vy += cw1 * cy
b.vx -= cw2 * cx
b.vy -= cw2 * cy
}
}
If I set the coordinates so that the circles overlap but still have their velocity both at 0, the circles won't push out each other, that is the problem. How do I fix this?
EDIT: Fiddle: http://jsfiddle.net/yP7xf/2/, click "Glitch it!" to see the glitch, as you see they won't separate.
sqrt(x) < y
thenx < y*y
. In your case, you can check ifdx*dx+dy*dy <= (a.r+b.r)*(a.r+b.r)
. Also you can precompute(a.r+b.r)*(a.r+b.r)
and only update it if/when one of the radiuses changes, then distance tests are very fast (2 multiplies, 1 add, and a compare --dx*dx+dy*dy <= a_plus_b_squared
). – Jannette