0

I am creating a game in XNA that will require thousands of tiny rectangles / squares to be drawn. As the number increases, the performance gets worse. Here is the code I am current using:

protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            foreach (SandBit sandBit in sandBitManager.grid)
            {
                Point p = sandBit.Position;
                spriteBatch.Draw(square, new Rectangle(p.X, p.Y, sandBit.SIZE, sandBit.SIZE), Color.White);
            }

            spriteBatch.End();
            base.Draw(gameTime);
        }

I am calling spriteBatch.Draw() for every single square, and I am redrawing the entire screen just to add a single square. I have done a significant amount of searching and I believe a solution is to draw to one texture and then call Draw() on that texture, but I cannot find relevant examples of this.

1 Answers1

0

Try not calling the Rectangle constructor in your draw function, you may get a large performance boost just from that (just use the same rectangle object over and over again, with different values set for the properties).

Given that this is a 2D game (no particles or anything) you may want to consider using a larger pre-generated texture for your sand instead of a ton of tiny rectangles. Having a huge enumeration in your draw loop will catch up with you eventually no matter what you do.

        Rectangle sandBitRect = new Rectangle()
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            foreach (SandBit sandBit in sandBitManager.grid)
            {
                Point p = sandBit.Position;
                sandBitRect.Left = p.X;
                sandBitRect.Top = p.Y;
                sandBitRect.Width = sandBit.SIZE;
                sandBitRect.Height = sandBit.SIZE;
                spriteBatch.Draw(square, sandBitRect, Color.White);
            }

            spriteBatch.End();
            base.Draw(gameTime);
        }
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Thanks, that has given me a significant performance boost. Am I going in the right direction if I say "draw many rectangles to Texture, draw texture once"? I read something like that in other threads but cannot find examples of dealing with large numbers of rectangles. – user3138018 Dec 27 '13 at 04:27
  • Even with that method, if you do a large enumeration (large to me would be 1K+) in your draw loop, you are going to take a performance hit (a larger one for larger enumerations). That being said you are going in the right direction. Drawing to a memory buffer and then bit-blitting to the screen is a good way to improve performance in GDI (though I can't remember the syntax for XNA). – BradleyDotNET Dec 27 '13 at 17:24