Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issues with laggy c# code in xna game studio

Tags:

c#

xna

My code seems to compile okay, but when I try to run it, it hangs very badly.

I've been following along with Riemers XNA tutorial here.

I'm pretty familiar with C#, but an expert by no means. I've had no problems getting any of this to work up to this point, and there are no errors or exceptions being thrown... it just hangs up. I've read on his related forum, where users discussed having other problems, usually relating to typos or code errors, but there's nothing like this in there... everyone seems to be able to run it fine.

Is there something I've done wrong perhaps? The nested for-loop at the bottom seems a bit heavy-handed to me. screenWidth and screenHeight are 500 and 500.

BTW: this is run from the LoadContent override method, so it should only run once as far as I know.

    private void GenerateTerrainContour()
    {
        terrainContour = new int[screenWidth];

        for (int x = 0; x < screenWidth; x++)
            terrainContour[x] = screenHeight / 2;
    }

    private void CreateForeground()
    {
        Color[] foregroundColors = new Color[screenWidth * screenHeight];

        for (int x = 0; x < screenWidth; x++)
        {
            for (int y = 0; y < screenHeight; y++)
            {
                if (y > terrainContour[x])
                    foregroundColors[x + y * screenWidth] = Color.Green;
                else
                    foregroundColors[x + y * screenWidth] = Color.Transparent;
                fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color);
                fgTexture.SetData(foregroundColors);
            }
        }
    }
like image 770
impyre Avatar asked Jan 17 '23 05:01

impyre


1 Answers

Probably something to do with the fact that you're creating 250,000 screen sized textures (holy moly)!

Resource allocation is always heavy - especially when you're dealing with media such as sounds and images.

It seems like you only really need one texture here, try moving fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color); outside of the loop. Then try moving fgTexture.SetData(foregroundColors); outside of the loop too.

private void CreateForeground()
{
    Color[] foregroundColors = new Color[screenWidth * screenHeight];

    fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color);

    for (int x = 0; x < screenWidth; x++)
    {
        for (int y = 0; y < screenHeight; y++)
        {
            if (y > terrainContour[x])
                foregroundColors[x + y * screenWidth] = Color.Green;
            else
                foregroundColors[x + y * screenWidth] = Color.Transparent;
        }
    }

    fgTexture.SetData(foregroundColors);
}
like image 124
MattDavey Avatar answered Jan 31 '23 05:01

MattDavey