2013-07-11 84 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