我使用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