我正在尝试用C#绘制一个瓷砖地图,我认为我遇到的问题很奇怪。
我有这个int数组,用于保存x坐标和y坐标以在屏幕上绘制切片。 (不仅有0的箭头是X而另一个是Y)
int[,] level1 = { { 0, 32, 64, 96 }, { 0, 0, 0, 0 } };
以下是我使用for循环将tile的一部分呈现到屏幕中的方法,并且我在这里得到一个“OutOfMemoryException”,我会注释掉:
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0;; x++)
{
for (int y = 0;; y++)
{
x = level1[x, 0];
y = level1[0, y];
//This line bellow is where it says OutOfMemoryException
spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
if (x >= 5 | y >= 5)
{
x = 0;
y = 0;
}
}
}
}
当我想调用这个渲染方法时,我在主类Render方法
中进行调用levelLoader.DrawTest(this.spriteBatch);
在我使用此DrawTest方法尝试绘制图块之前,它完美运行。但我完全不知道为什么这不能正常工作。
更新
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0; x < 5 ; x++)
{
for (int y = 0; y < 5 ; y++)
{
x = level1[x, 0];
y = level1[0, y];
spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
}
}
}
UPDATE2:
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0; x < 5 ; x++)
{
for (int y = 0; y < 5 ; y++)
{
int tileXCord = level1[x, 0];
int tileYCord = level1[0, y];
spriteBatch.Draw(tileSheet, new Rectangle(tileXCord, tileYCord, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
}
}
}
答案 0 :(得分:2)
我在您的代码中看到了几个问题:
spriteBatch.Draw()
方法不会绘制任何内容,只会安排精灵的绘制。此方法调用应以spriteBatch.Begin()
开头(开始计划绘图),最后您必须调用spriteBatch.End()
将计划的spites刷新到您的设备。无限循环导致精灵绘图的无限调度,直到内存已满并且您面临内存不足异常。(x >= 5 | y >= 5)
中你正在使用按位OR 比较,你不应该这样做(除非是故意的,我在这里看不到,而是使用布尔OR:(x >= 5 || y >= 5)
我会以这种方式重写您的代码
spriteBatch.Begin();
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
x = level1[x, 0];
y = level1[0, y];
//This line bellow is where it says OutOfMemoryException
spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
}
}
spriteBatch.End();
它将在主游戏循环的每个Draw()
事件中重新绘制所有磁贴(前提是您仍然使用Draw()
类的Game
方法调用此方法.XNA会有所不同FPS速率取决于您PC的性能以及每帧必须进行的计算量。
答案 1 :(得分:0)
我认为你陷入无限循环。您需要以某种方式退出以避免内存不足异常。