2011-01-30 70 views
1

我有一個小遊戲(5班)正在XNA開發。有些球在窗戶周圍彈跳,當與窗戶兩側碰撞時以直角移動。用戶通過在窗口中的任何位置拖動鼠標來創建一個選取框。當選取框被創建並確認時,每當球擊中選取框時,它將被移除。我有我的球在一個二維數組,我想知道如何從這種類型的數組中刪除球。目前我正在做以下操作:如何根據隨機條件從二維數組中刪除項目?

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

爲什麼球在二維數組(而不是一維)?只是好奇 – Cameron 2011-01-30 20:27:22

回答

1

您可以設置球在null的位置。這很快且簡單(不需要調整數組大小),但是您必須先更改所有循環以檢查空值。

因此,代碼會是這個樣子:

if (ball.Intersects(marquee)) 
{ 
    var deadBall = balls[rowIndex, columnIndex]; 
    balls[rowIndex, columnIndex] = null; 

    deadBall.SetRed(0); 
    deadBall.SetGreen(0); 
    deadBall.SetBlue(0); 
} 

請記住,您可以跟蹤球計數的獨立變量;這比計算陣列中非空球的數量更容易(也更快)。

0

如果你需要刪除項目,使用列表,除非有一些需要有一個靜態大小的二維數組的球。你提到他們在屏幕周圍彈跳,所以似乎沒有必要將它們保持在行/列中。

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); 

爲了減少代碼量你必須寫,我還修改你的球類包括一些更多的功能,如:

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); 
    } 
}