我正在嘗試編寫一個Java程序來支持離格外擴散有限的融合仿真。用於模擬移動粒子的基本代碼已到位,直到所述粒子碰到靜態中心粒子。在這一點上,我試圖確保移動的粒子剛剛接觸(切線)靜態粒子。但是,由於不明原因,它有時會失敗(8個粒子中的前2個相交,其他6個很好)。圓圈碰撞
下面是代碼:
boolean killed, collide;
double xp, yp, dx, dy, theta, xpp, ypp, length;
int xc = 200;
int yc = 200;
int killRadius = 200;
int releaseRadius = 150;
int partRadius = 14;
int partDiam = 2 * partRadius;
drawCircle(xc, yc, killRadius); // kill
drawCircle(xc, yc, releaseRadius); // release
drawCircle(xc, yc, partRadius); // center particle
//while (true) {
killed = false;
collide = false;
theta = Math.random() * Math.PI * 2;
xp = xc + releaseRadius * Math.cos(theta);
yp = yc + releaseRadius * Math.sin(theta);
while (true) {
theta = Math.random() * Math.PI * 2;
length = partDiam;
xpp = xp;
ypp = yp;
xp = xp + length * Math.cos(theta);
yp = yp + length * Math.sin(theta);
//drawCircle((int) xp, (int) yp, partRadius);
// Should it be killed ? (maybe could use a box to fasten
// computations...
// Would switching the test for kill w test for collision
// improve perf ?
dx = xp - xc;
dy = yp - yc;
if ((dx * dx) + (dy * dy) > killRadius * killRadius) {
killed = true;
break;
}
// Does it collide with center? replace by any particle...
dx = xp - xc;
dy = yp - yc;
if ((dx * dx) + (dy * dy) < (partDiam) * (partDiam)) {
collide = true;
break;
}
}
// Probably something is wrong here...
if (collide) {
// no absolute value because particles move at most by diameter
double depthPenetration = partDiam
- Math.sqrt((dx * dx) + (dy * dy));
dx = xpp - xp;
dy = ypp - yp;
// shorten distance travelled by penetration length to ensure
// that
// particle is tangeant
length = Math.sqrt((dx * dx) + (dy * dy)) - depthPenetration;
xp = xpp + length * Math.cos(theta);
yp = ypp + length * Math.sin(theta);
drawCircle((int) xp, (int) yp, partRadius);
}
//}
當然,我問前檢查許多引用,但不能發現任何錯誤的代碼...幫助將不勝感激。
我調試的代碼太多。我們先從 - 你得到什麼輸出,你期望什麼? – djechlin
如果我是你,我會創建一系列測試計算的單元測試。 –
我不得不承認我仍然很難理解你正在努力完成什麼,而不是你想要解決的問題。什麼是有問題的症狀,你期望什麼,並且你得到了什麼? – trumpetlicks