4

我的代码似乎可以编译,但是当我尝试运行它时,它挂得很严重。

我一直在关注 Riemers XNA教程

我对 C# 非常熟悉,但绝不是专家。到目前为止,我没有遇到任何问题,并且没有抛出任何错误或异常......它只是挂断了。我在他的相关论坛上读过,用户讨论了其他问题,通常与拼写错误或代码错误有关,但那里没有这样的东西......每个人似乎都能很好地运行它。

也许我做错了什么?底部的嵌套 for 循环对我来说似乎有点笨拙。screenWidth 和 screenHeight 分别为 500 和 500。

顺便说一句:这是从 LoadContent 覆盖方法运行的,所以据我所知,它应该只运行一次。

    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);
            }
        }
    }
4

2 回答 2

6

可能与您正在创建 250,000 个屏幕大小的纹理(天哪)有关!

资源分配总是很繁重——尤其是在处理声音和图像等媒体时。

似乎您在这里只需要一种纹理,请尝试移出fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color);循环。然后尝试移动fgTexture.SetData(foregroundColors);到循环之外。

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);
}
于 2012-07-03T20:30:28.390 回答
3
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;
    }
 }

 foregroundTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color);
 foregroundTexture.SetData(foregroundColors);

你的问题在最后两行。在您的循环中,您正在创建500 x 500 Texture2D的对象,这会减慢您的速度。将它们移到 for 循环之外。

于 2012-07-03T20:32:58.340 回答