【发布时间】:2015-10-02 06:10:01
【问题描述】:
我正在 XNA 4.0 中使用 C# 制作 Space Invaders 克隆,但遇到了几个问题。第一个是当我射击阵列右侧一列但最上面的所有入侵者时,入侵者会移出屏幕,直到下一列达到预定限制;然后整个阵列向下移动。显然我希望它仍然能够检测到剩余的入侵者。我很确定问题出在以下代码部分,但我不确定问题出在哪里。
for (int rows = 4; rows > 0; rows--) // Detects right-most invader
for (int cols = 10; cols > 0; cols--)
{
if (InvaderArray[rows, cols] != null)
{
RightInvader = InvaderArray[rows, cols];
break;
}
}
第二个问题是,如果我摧毁除一行入侵者之外的所有入侵者,我会在这段代码上收到“NullReferenceException was unhandled”通知:
if (RightInvader.GetXPos() > 800) // Right edge limit
{
InvaderDir = -1;
for (int rows = 0; rows < 5; rows++)
for (int cols = 0; cols < 11; cols++)
{
if (InvaderArray[rows, cols] != null)
{
InvaderArray[rows, cols].MoveVertical(8);
}
}
}
再次,不确定问题是什么。以下是检测剩余入侵者的代码:
// Detecting remaining invader
bool InvaderFound = false;
for (int rows = 0; rows < 5; rows++)
for (int cols = 0; cols < 11; cols++)
{
if (InvaderArray[rows, cols] != null)
{
InvaderFound = true;
break;
}
}
非常感谢您对这两个问题的任何帮助。
【问题讨论】:
-
您的第一个循环没有在 0 索引中迭代,这是预期的行为吗?不应该是 rows >= 0 和 cols >=0?
-
另外,您的
break语句只会中断内部循环。外循环继续,这可能不是你想要的。引入一个变量来决定是否继续外循环。如果没有找到合适的元素,RightInvader可能是null。你应该在访问它的GetXPos()之前检查一下。 -
当您“杀死”入侵者时,您可能需要发布用于修改 InvaderArray 的代码。您是否将其设置为 null 或其他值?