保持圆圈不重叠

时间:2013-07-11 18:23:14

标签: javascript math canvas geometry

我正在试图找出JavaScript数学,以便将两个碰撞的圆圈彼此分开。

此图片的左侧是我已有的视觉表现:

http://i.imgur.com/FMv1G3O.png

x1,y1,x2和y2是圆的位置,r1和r2是圆的半径,θ是圆之间相对于画布的x轴的角度。

如何计算两个圆圈的新[x,y]位置,以便它们相互“推”开,如图像右侧所示?

我还计划让较小的圆圈比较大的圆圈推得更多。通过使用它们的归一化半径作为乘数,这应该很容易。

1 个答案:

答案 0 :(得分:5)

// 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; 
}