Search code examples
c#arraysxnacollision-detectionrectangles

Index out of range for rectangle array?


I have this problem with assigning individual rectangles to each value in an list. To try this out I first tried to give a rectangle to value 5.

snakeBodyRectangleArray[5] = new Rectangle((int)snakeBodyArray[5].X, (int)snakeBodyArray[5].Y, textureSnakeBody.Width, textureSnakeBody.Height);
// above is in update 
protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        graphics.PreferredBackBufferWidth = 500;
        graphics.PreferredBackBufferHeight = 500;
        graphics.IsFullScreen = false;
        graphics.ApplyChanges();
        Window.Title = "Curvy Snake";

        snakeBodyArray = new List<Vector2>();
        snakeBodyRectangleArray = new List<Rectangle>();

        bodyTimer.Elapsed += new ElapsedEventHandler(updateBodyPositions);
        bodyTimer.Interval = 120;
        bodyTimer.Enabled = true;

        base.Initialize();
    }

If you need more code, just ask.

thanks in advance


Solution

  • I used

    snakeBodyRectangleArray[bodyNumber] = new Rectangle((int)snakeBodyArray[bodyNumber].X, (int)snakeBodyArray[bodyNumber].Y, textureSnakeBody.Width, textureSnakeBody.Height);
    

    and put it into a private void.