【发布时间】:2013-01-14 05:15:16
【问题描述】:
我有一个弹跳球应用程序,我必须扩展它以防止球重叠。
当球与另一个球重叠时,它们应该像在现实生活中一样移开。
我必须扩展给定的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, radius, prevX, prevY 声明为 int。
重叠,距离加倍。
当 2 个重叠时,它们会卡住。为什么?
很遗憾,由于模块太多,我无法上传所有源代码。 我正在使用 Visual C# Express 2010。
【问题讨论】:
-
很遗憾,您在此处编写的内容不适合 Stack Overflow。您需要首先减少问题;找出出错的代码,然后构造一个minimal test-case 来演示它。一个测试用例包括输入和输出。
-
您的问题是什么?我已经阅读了您的代码和课程,但我无法区分您要解决的确切问题。您是否要求某人提供完整的解决方案 - 如果没有,请提供该问题的更具体细节,因为它看起来有点像您。从描述对象模型和接口开始,这样人们就可以理解如何引用和调用方法来询问(并可能改变状态)每个
Ball -
@JustinJDavies 当球重叠而不是移开时,它们有点卡住了。这就是问题所在。