我有一個彈跳球的應用程序,我必須擴展它以防止重疊的球。執行彈跳球碰撞檢測
當球與另一個球重疊時,他們應該離開現實生活。
我不得不延長給定MoveBall
方法:
private void MoveBall()
{
prevX = x;
prevY = y;
x += xVelocity;
y += yVelocity;
// Is there too closed ball?
foreach (Ball ball in parentForm.balls)
{
distance = Math.Sqrt(Math.Pow((double)(ball.prevX - prevX), 2) +
Math.Pow((double)(ball.prevY- prevY), 2));
overlap = ((radius + ball.radius) - distance);// +ball.radius;
if (ball.id != this.id &&
ball.id != lastID &&
overlap > 0)
{
lastID = this.id;
if (xVelocity > 0) // roading right
{
xVelocity = -xVelocity;
x -= xVelocity - ball.xVelocity;
}
else if (xVelocity <= 0) // roading left
{
xVelocity = -xVelocity;
x += xVelocity + ball.xVelocity;
}
if (yVelocity > 0)
{ // going up
yVelocity = -yVelocity;
y -= yVelocity - ball.yVelocity;
}
else if (yVelocity <= 0) // down
{
yVelocity = -yVelocity;
y += yVelocity + ball.yVelocity;
}
}
}
// ***********************************************
// ***************** END MY CODE *****************
if (x > parentForm.Width - 10 - (radius) || x < 0)
{
if (x < 0) x = 0;
if (x > parentForm.Width - 10) x = parentForm.Width - 10 - radius;
xVelocity = -xVelocity;
}
if (y > parentForm.Height - 40 - (radius) || y < 0)
{
if (y < 0) y = 0;
if (y > parentForm.Height - 40) y = parentForm.Height - 40 - (radius);
yVelocity = -yVelocity;
}
}
X,Y,xVelocity,yVelocity,半徑,prevX,prevY聲明爲INT。
重疊,距離爲一倍。
當2重疊時,它們會卡住。爲什麼?
不幸的是,我不能上傳所有的源代碼,因爲有很多模塊。 我正在使用Visual C#Express 2010.
不幸的是,你在這裏寫的東西並不適合Stack Overflow。你需要先解決問題;找出出錯的代碼,然後構造一個[** minimal ** test-case](http://sscce.org)來演示它。測試案例包括輸入和輸出。 –
你的問題是什麼?我讀過你的代碼和班級,我無法區分你想要解決的問題。您是否要求某人提供完整的解決方案 - 如果沒有,請提供該問題的更具體細節,因爲它看起來有點像您。 首先描述對象模型和接口,以便人們可以理解如何引用和調用方法來詢問(並可能改變狀態)每個'Ball' – JustinJDavies
@JustinJDavies當球重疊時,搬走。這是問題。 – Billie