Trouble with collision detection in XNA?
Posted
by
Lewis Wilcock
on Game Development
See other posts from Game Development
or by Lewis Wilcock
Published on 2012-12-08T17:22:07Z
Indexed on
2012/12/08
23:38 UTC
Read the original article
Hit count: 192
I'm trying to loop through an list of enemies (enemyList) and then any that have intersected the rectangle belonging to the box object (Which doesn't move), declare there IsAlive bool as false. Then another part of the code removes any enemies that have the IsAlive bool as false.
The problem im having is getting access to the variable that holds the Rectangle (named boundingBox) of the enemy. When this is in a foreach loop it works fine, as the enemy class is declared within the foreach. However, there are issues in using the foreach as it removes more than one of the enemies at once (Usually at positions 0 and 2, 1 and 3, etc...).
I was wondering the best way to declare the enemy class, without it actually creating new instances of the class? Heres the code I currently have:
if (keyboardState.IsKeyDown(Keys.Q) && oldKeyState.IsKeyUp(Keys.Q))
{
enemyList.Add(new enemy(textureList.ElementAt(randText), new Vector2(250, 250), graphics));
}
//foreach (enemy enemy in enemyList)
//{
for (int i = 0; i < enemyList.Count; i++)
{
if (***enemy.boundingBox***.Intersects(theDefence.boxRectangle))
{
enemyList[i].IsDead = true;
i++;
}
}
//}
for(int j = enemyList.Count - 1; j >= 0; j--)
{
if(enemyList[j].IsDead)
enemyList.RemoveAt(j);
}
(The enemy.boundingBox is the variables I can't get access too).
This is a complete copy of the code (Zipped) If it helps:
https://www.dropbox.com/s/ih52k4e21g98j3k/Collision%20tests.rar
I managed to find the issue. Changed enemy.boundingBox to enemyList[i].boundingBox. Collision works now! Thanks for any help!
© Game Development or respective owner