// Just take the vector difference between the centers
var dx = x2 - x1;
var dy = y2 - y1;
// compute the length of this vector
var L = Math.sqrt(dx*dx + dy*dy);
// compute the amount you need to move
var step = r1 + r2 - L;
// if there is a collision you will have step > 0
if (step > 0) {
// In this case normalize the vector
dx /= L; dy /= L;
// and then move the two centers apart
x1 -= dx*step/2; y1 -= dy*step/2;
x2 += dx*step/2; y2 += dy*step/2;
}
Run Code Online (Sandbox Code Playgroud)