2013-07-11 73 views
2

我想弄清楚JavaScript数学移动两个相互碰撞的圆圈。保持重叠的圆圈

这一形象的左边是什么,我已经有一个直观表示:

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

X1,Y1,X2和Y2是圆的位置,R1和R2为半径θ是相对于画布的x轴的圆之间的角度。

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

我还计划让小圆圈比大圆圈更大。通过使用标准化半径作为乘数,这应该很容易。

回答

3
// 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; 
} 
+0

完美地工作!谢谢 :) – thykka