我正在尝试找出JavaScript数学,以使两个碰撞的圈彼此分开。

该图像的左侧是我已经拥有的视觉表示:

x1,y1,x2和y2是圆的位置,r1和r2是圆的半径,theta是圆之间相对于 Canvas x轴的 Angular 。

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

我还计划使较小的圆圈比较大的圆圈受到更大的 push 。通过将其归一化半径用作乘数,这应该足够容易。

最佳答案

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

10-07 19:22
查看更多