0

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;

                    }
                }
            }
        }
JML
  • 951
  • 1
  • 7
  • 11

2 Answers2

0

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:

for (int j = i+1; j < birds.Count; j++)

and then you can remove the if (j > i) (j will always be > i). Other thing that I would recommend is not declaring int j in the for statement. It's always better to having it declared outside than instancing on every i, so:

int i, j;
for (i = 0; i < birds.Count; i++)
      for (j = i+1; j < birds.Count; j++)

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)

Community
  • 1
  • 1
Pablo Ariel
  • 251
  • 3
  • 16
0

Your problem is that when comparing rectangles you set the bird to white, even if it was previously set to yellow by a previous hit detection, so it may have been set to yellow, but it'll be set back again if the last test fails.

How about at the start of each frame (before collision detection) set the rectangles to white then if you get a collision set them to yellow (leaving them alone if there's no collision).

George Duckett
  • 31,770
  • 9
  • 95
  • 162