-1

So I am working on a game, aside from a game engine, and I have a for loop to detect collisions with all objects in a list of Panels

Here is the code:

for (int x = 1; x <= 2; x++)
{
    if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
    {
       MessageBox.Show("COLLIDING");
    }
}

Currently there are only two objects added to the list called walls And everytime I go to run it tells me Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index I don't know what to do, am I setting up the if statement wrong?

I just tried taking it out of the for loop and replaced x with 0, and when I touched that object it said I was colliding, so I know I didn't set up the if statement wrong.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Engine Dev
  • 129
  • 1
  • 10

3 Answers3

3

As you may or may not know, arrays start at 0 in the index, so your array should be like so.

for (int x = 0; x < 2; x++) 
{
    if (player.obj.Bounds.IntersectsWith(walls[x].Bounds)) 
    {
        MessageBox.Show("COLLIDING");
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
C. Knapp
  • 74
  • 3
1

If there are 2 objects in walls the loop needs not go to x = 2

  for (int x = 0; x < 2; x++)
        {
            if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
            {
                MessageBox.Show("COLLIDING");
            }
        }

As Arrays start at index 0

Ya Wang
  • 1,758
  • 1
  • 19
  • 41
0

You have two elements in the walls[] array means they ware located in walls[0] and walls[1]( Since .Net arrays are following 0 based indexing) and hence walls[2] is out of bound; So you should start the loop with 0 to get the first element and loop up to 2. But i strongly recommend you to use length of walls instead of 2

for (int x = 0; x < walls.Length; x++)
{
    if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
    {
        MessageBox.Show("COLLIDING");
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88