我正在尝试检测敌人对象列表上的碰撞,但是它只能处理最后创建的对象。我试过了两个:
for (int i = 0; i < enemies.Count; i++)
{
if (IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData))
{
touched = true;
}
else
{
touched = false;
}
}
并且:
foreach (Enemy enemy in enemies)
{
if (IntersectsPixel(player.rectangle, player.textureData, enemy.rectangle, enemy.textureData))
{
touched = true;
}
else
{
touched = false;
}
}
我将其放入Update方法中。每隔几秒就会创建一次敌人,所以我知道检测工作正常,但是一旦出现下一个,最后一个就会停止工作......
答案 0 :(得分:4)
你只检查最后一项,你必须在IntersectsPixel
为真时处理循环,并处理对象
for (int i = 0; i < enemies.Count; i++)
{
if (IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData))
{
touched = true;
break;
}
}
或使用linq收集所有这样的对象:
var resTrue = enemies.Where(x=>x.IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData)).ToList();
var resFalse = enemies.Where(x=>!x.IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData)).ToList();
答案 1 :(得分:2)
为什么不在bool Touched
中实现属性class Enemy
?
这样,您可以像这样更改代码:
if (/*check for collision*/)
enemy.Touched = true;
更好的是,实现方法Touched
,而不是OnTouched(/*arguments*/)
,所以你可以这样做:
if (/*check for collision*/)
enemy.OnTouched(/*arguments*/); // Which would perform any and all necessary actions on the touched object