我在XNA开发了一个小游戏(5个类)。窗户周围有球,在与窗户两侧碰撞时以直角移动。用户通过将鼠标拖动到窗口中的任何位置来创建选取框。当创建并确认选框时,每次球击中选框时都要将其移除。我把球放在一个二维阵列中,我想知道如何从这种类型的阵列中移除球。目前我正在做以下事情:
Rectangle ball = new Rectangle((moveBallX - 4), (moveBallY - 4), moveBallX, moveBallY);
Rectangle marquee = new Rectangle(tempInitialX, tempInitialY, tempWidth, tempHeight);
if (ball.Intersects(marquee))
{
balls[rowIndex, columnIndex].SetRed(0);
balls[rowIndex, columnIndex].SetGreen(0);
balls[rowIndex, columnIndex].SetBlue(0);
}
这使得进入选框的球变黑,因此它们变得不可见。我想用代码做其他事情,例如显示板上剩余的球数,因此能够从阵列中删除项目将非常有用。
感谢您的时间。
答案 0 :(得分:1)
您可以将球的位置设置为null
。这是快速而简单的(不需要调整数组大小),但您必须先更改所有循环以首先检查空值。
所以代码看起来像这样:
if (ball.Intersects(marquee))
{
var deadBall = balls[rowIndex, columnIndex];
balls[rowIndex, columnIndex] = null;
deadBall.SetRed(0);
deadBall.SetGreen(0);
deadBall.SetBlue(0);
}
请记住,您可以在单独的变量中跟踪球数;这比计算数组中非空球的数量更容易(也更快)。
答案 1 :(得分:0)
如果你需要删除项目,请使用List,除非需要有一个静态大小的2D阵列球。你提到它们在屏幕上弹跳,所以似乎没有必要将它们保存在行/列表中。
List<Ball> balls = new List<Ball>();
// Initialize the balls into a grid structure:
for( int i=0; i < numberOfRows; i++ )
for( int j=0; j < numberOfColumns; j++ )
balls.Add( new Ball( i * gridWidth, j * gridHeight, Color.Blue );
// ... some other code probably goes here ...
var trash = balls.Where( ball => ball.Intersects( marquee ) );
foreach( Rectangle ball in trash )
balls.Remove( ball );
为了减少你必须编写的代码量,我还要修改你的Ball类以包含更多函数,如下所示:
public class Ball
{
int X;
int Y;
Color color;
public Ball( int x, int y, Color c )
{
X = x; Y = y; color = c;
}
// Whatever else you have in your ball class goes here
public bool Intersects( Rectangle rect )
{
return new Rectangle( this.X - 4, this.Y - 4, this.X, this.Y ).Intersects( rect );
}
public void MakeInvisible()
{
color = new Color( 0, 0, 0, 0 );
}
}