我正在尝试boundingBoxes
在敌人和被击中的子弹之间创建(碰撞)。不幸的是,System.ArgumentOutOfRangeException
每当敌人离开屏幕,或者一次产生多于1个子弹时,都会向我显示错误消息。
这两个边界框都是在Update
子弹和敌人类的功能中创建的,如下所示:
boundingBox = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
这是我的Game1
更新功能中使用的相关代码:
for (int i = bullets.Count - 1; i >= 0; i--)
{
bullets[i].Update(gameTime);
ERROR OCCURS HERE -> if (bullets[i].boundingBox.Intersects(enemies[i].boundingBox))
{
score += 1;
bullets.RemoveAt(i);
}
//Bullets being destroyed upon leaving
if (bullets[i].position.Y < 0)
bullets.RemoveAt(i);
}
任何帮助,将不胜感激。
另外,Game1
如果这完全有帮助,这是我如何在项目类中实现项目符号列表?:
List<Bullet> bullets = new List<Bullet>();
public void Shoot (Vector2 pos, Vector2 dir, float speed)
{
Bullet bullet = new Bullet(bulletTexture);
bullet.position = pos;
bullet.direction = dir;
bullet.speed = speed;
if (bullets.Count() < 40) //Maximum amount of bullets
bullets.Add(bullet);
}
如果我必须猜测,则错误来自该if (bullets[i].boundingBox.Intersects(enemies[i].boundingBox))
语句。
基本上,您是否一直都有相同数量的敌人和子弹?如果不是,那么每当数字不同时,它将失败。
为什么是这样?好的,您要使用两个不同的collectionbullets
和enemies
,并将element放在position i
。
因此,如果集合中只有5个子弹而只有1个敌人,则for的第一次迭代将具有i = 4
,该位置在enemies
集合中不存在(仅具有该enemies[0]
位置)。
解决问题的一种方法是:
foreach (enemy in enemies)
foreach (bullet in bullets)
if (bullet.boundingBox.Intersects(enemy.boundingBox))
{
// do your logic here.
}
您穿过每个敌人,然后检查每个敌人是否有子弹相交。这不是最佳的解决方案性能明智的选择,但我认为这是一个好的开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句