[英]How do I remove items from a 2-d array based on randomised conditions?
我有一個用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);
}
這會使進入選框的球變黑,從而使它們變得不可見。 我想用代碼做其他事情,例如顯示板上剩余的球數,因此能夠從數組中刪除項目將很有用。
謝謝你的時間。
您可以在數組中將球設置為null
。 這既快速又簡單(不需要調整數組大小),但是您必須更改所有循環才能首先檢查空值。
因此代碼看起來像這樣:
if (ball.Intersects(marquee))
{
var deadBall = balls[rowIndex, columnIndex];
balls[rowIndex, columnIndex] = null;
deadBall.SetRed(0);
deadBall.SetGreen(0);
deadBall.SetBlue(0);
}
請記住,您可以在一個單獨的變量中跟蹤球數; 這比計算數組中非空球的數量更容易(並且更快)。
如果您需要刪除項目,請使用“列表”,除非有些需要具有靜態尺寸的二維球陣列。 您提到它們雖然在屏幕上彈跳,所以似乎沒有必要將它們保持在行/列cel中。
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 );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.