我使用XNA製作坦克遊戲。我已經實現了使用列表拍攝子彈的功能。拍攝後,我想測試子彈是否已經接近屏幕的邊界。如果是這樣,從列表中刪除特定的項目符號。C# - >索引超出範圍錯誤|使用列表
只有當我在任何給定時間在屏幕上有多個子彈時纔會出現此錯誤。下面是代碼:
坦克類:
List<Bullet> bulletList = new List<Bullet>();
bool spacebarPrepared = true; //for shooting every 0.5 seconds
short count = 0;
//Shoot
if (Keyboard.GetState().IsKeyDown(Keys.Space) && spacebarPrepared == true)
{
bulletList.Add(new Bullet(sprBullet, position, turretDirection, turretAngle));
spacebarPrepared = false;
}
if (spacebarPrepared == false)
{
spacebarCount += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (spacebarCount > 0.5)
{
spacebarPrepared = true;
spacebarCount = 0;
}
}
//Update bullets
foreach (Bullet bullet in bulletList)
{
bullet.Update(bounds);
}
count = (short)bulletList.Count;
//Remove unwanted bullets
for (short i = 0; i < count; i++)
{
if (bulletList[i].Alive == false)
{
bulletList.Remove(bulletList[i]);
}
}
子彈類:
class Bullet
{
Texture2D spr;
Vector2 origin, pos, dir, turretLength;
float rotation, scale, turretLeng;
short speed;
bool alive = true;
public Bullet(Texture2D sprite, Vector2 position, Vector2 direction, float angle)
{
spr = sprite;
scale = 0.15f;
turretLeng = (110 + spr.Width) * scale;
speed = 5;
rotation = angle;
pos = position;
dir = direction;
origin = new Vector2(spr.Width/2, spr.Height/2);
FindTurretLength();
}
public void Draw(SpriteBatch spriteBatch)
{
Matrix bulletTranslation = Matrix.CreateRotationZ(rotation) * Matrix.CreateTranslation(pos.X + turretLength.X, pos.Y + turretLength.Y, 0);
spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, bulletTranslation);
spriteBatch.Draw(spr, Vector2.Zero, null, Color.White, 0, origin, 0.15f, SpriteEffects.None, 1f);
spriteBatch.End();
}
public void Update(Vector2 boundary)
{
pos += dir * speed;
if (pos.X < 50 || pos.X > boundary.X - 50 || pos.Y < 50 || pos.Y > boundary.Y - 50)
{
alive = false;
}
}
public void FindTurretLength()
{
turretLength = new Vector2(turretLeng * dir.X, turretLeng * dir.Y);
}
public Vector2 Pos
{
get
{
return pos;
}
set
{
pos = value;
}
}
public bool Alive
{
get
{
return alive;
}
set
{
alive = value;
}
}
}
後來我發現自己調試是,當我自己的 '計數' 變量= 2,但bulletList.Count = 1.這可能是問題嗎?這是怎麼發生的?
任何幫助,非常感謝。
這種錯誤發生。你應該能夠通過調試和檢查它正在被拋出的行來弄清楚發生了什麼,然後反向工作並逐步查看代碼是如何執行的。 – 2014-11-03 20:32:25
另外,爲什麼你要把'count'聲明爲'short'?看來「int」會更自然。 – 2014-11-03 20:47:42
你不瞭解什麼樣的例外情況? Visual Studio將顯示鏈接,同時在線調試以獲取更多幫助 – MickyD 2014-11-04 06:23:45