Question

I would like to iterate through an array that covers every pixel on my screen. i.e:

        for (int y = 598; y > 0; y--)
        {
            for (int x = 798; x > 0; x--)
            {
                if (grains[x][y])
                {
                    spriteBatch.Draw(Grain, new Vector2(x,y), Color.White);
                }
            }
        }

...my texture is a 1x1 pixel image that is drawn to the screen when the array value is true. It runs decent -- but there is definitely lag the more screen I cover. Is there a better way to accomplish what I am trying to achieve?

Was it helpful?

Solution

Instead of using X x Y individual sprites, create a single image, and set the pixels appropriately. Then just render the entire image as a texture on a single sprite.

The jagged array is most likely not the problem - rather the nearly half-million sprites.

OTHER TIPS

The problem is that you're spending alot of CPU time within the drawing method each frame. The Draw method of your Game instance will always be called as often as possible, whether in Fixed Time or not. Given that, you always want to make sure you're spending as little time there as possible, which means you want to place most of the work on the GPU.

The nested for-loops as well as all the calls to spriteBatch.Draw are going to use the much slower CPU, especially when your loop gets bigger and bigger, which means delayed drawing.

If you want to do per-pixel calculations, per Draw, each frame, then the best way to go about it is to place the work on the GPU and use a pixel shader. You could accomplish your own problem by creating one texture the size you want and passing an array to the shader that holds your "on or off" information, among other ways to accomplish the same goal.

How To: Apply a Pixel Shader to Sprites

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top