I have a List of objects of which all have a bounding rectangle updated everytime… How can I effectively iterate among them ? I thought that checking it like this is fine but any ideas ?
for (int i = 0; i < birds.Count; i++)
{
for (int j = 0; j < birds.Count; j++)
{
if (j > i)
{
if (birds[j].boundingRectangle.Intersects(birds[i].boundingRectangle))
{
birds[i].tintColor = Color.Yellow;
birds[j].tintColor = Color.Yellow;
}
else
{
birds[i].tintColor = Color.White;
birds[j].tintColor = Color.White;
}
}
}
}
I can’t see there why it would fail to detect the collision, the code seems to be ok. You should output some string showing the values of the bounding rectangles to see if they’re properly set, or if you are executing that code at all, or if your “birds” array survives the scope in where this code is executed (you may be modifying a copy instead of the actual array).
As for improvements, you can do:
and then you can remove the
if (j > i)(j will always be > i).Other thing that I would recommend is not declaring
int jin theforstatement. It’s always better to having it declared outside than instancing on everyi, so:I don’t think there is much more room for improvement there without being able to use pointers. Your method is fine for 2D graphics anyway, unless you’re checking for hundreds of objects.
PS: I believe your question could fit in the Game Development – SE site (unless you’re using XNA and bounding boxes for something else :P)