避免圆形重叠的方法

4
我正在尝试计算JavaScript数学,以使两个碰撞的圆彼此分开。图片左侧是我已有的可视化表示:
x1、y1、x2和y2是圆的位置,r1和r2是圆的半径,θ是圆之间与画布x轴的夹角。
请问如何计算两个圆的新[x,y]位置,以使它们像图像右侧所示一样“推”彼此分开?
我还打算让较小的圆被推得比较大的圆更远。可以通过使用它们的规范化半径作为乘数来实现这一点。
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接