I have a loop that is supposed to detect and remove any objects in a list that intersect with an object being placed. The code is as follows:
for (int i = 0; i < levelObjects.Count(); i++)
{
if (levelObjects[i].BoundingBox.Intersects(mouseBlock.BoundingBox))
{
levelObjects.RemoveAt(i);
}
}
When encountering a situation where there are multiple collisions, it sometimes does not detect the collision. The intersection function is working fine. What is it about my loop that’s causing this?
Since you’re removing from the loop, you end up skipping elements. A better option would be to loop backwards:
This prevents the “skipped” object that you’re missing now, since when you remove, and the indices shift downwards, you’re only shifting objects whom you’ve already tested.