我用 C#/Monogame 编写了一个小程序,它允许我通过键盘命令移动棋盘上的棋子。一次一块瓷砖。
在测试代码时,我注意到,有时程序有几秒钟无法接收键盘。当程序恢复运行时,它不会播放所有错过的输入,而是假装什么都没发生。
为了弄清楚这一点,我将 printline 命令放入更新方法中,如下所示:
public override void Update(GameTime gameTime)
{
if (Globals.WorldTime_s - lastSlowUpdate >= 1)//once per second
{
lastSlowUpdate = Globals.WorldTime_s;
Debug.WriteLine($"PlayerTurn: {lastSlowUpdate}");
}
}
世界时间在Globals类中是这样更新的,是静态的:
public static void Update(GameTime gameTime)
{
_worldTime_s += gameTime.ElapsedGameTime.TotalSeconds;
}
我看到的是以下内容:在 5 秒左右的时间里,我每秒都会收到一条 printLine,时间戳间隔为 1 秒,正如预期的那样。然后大约 2 或 3 秒内没有任何反应,直到下一个 printLine 到来。下一个时间戳是上一个时间戳加 1 秒。在这个间隙中,开关也不会响应键盘。
我相信问题出在 Visual Studio(2022,版本 17.10.4)中,因为代码正在执行其应该执行的操作。
即使对于我的小“Hello world”玩具程序来说,这正常吗?我该如何改进这个?如果软件不能可靠地响应键盘,测试软件就会变得困难。
我发现了我的问题。解决办法就是改变
public void Draw(GameTime gameTime)
{
for (int x = 0; x < MapSize.X; x++)
{
for (int y = 0; y < MapSize.Y; ++y)
{
Color color;
if (tiles[x][y].collision) { color = ColorWall; }
else { color = ColorOpen; }
Texture2D texture = new Texture2D(Globals.GraphicsDevice, 1, 1);
texture.SetData<Color>(new Color[] { color });
Rectangle targetRect = new Rectangle(x * TileSize + 1, y * TileSize + 1, TileSize - 2, TileSize - 2);
Rectangle sourceRect = new Rectangle(0, 0, 1, 1);
Globals.SpriteBatch.Draw(texture, targetRect, sourceRect, Color.White);
}
}
进入
public void Draw(GameTime gameTime)
{
Texture2D texture = new Texture2D(Globals.GraphicsDevice, 1, 1);
for (int x = 0; x < MapSize.X; x++)
{
for (int y = 0; y < MapSize.Y; ++y)
{
Color color;
if (tiles[x][y].collision) { color = ColorWall; }
else { color = ColorOpen; }
texture.SetData<Color>(new Color[] { color });
Rectangle targetRect = new Rectangle(x * TileSize + 1, y * TileSize + 1, TileSize - 2, TileSize - 2);
Rectangle sourceRect = new Rectangle(0, 0, 1, 1);
Globals.SpriteBatch.Draw(texture, targetRect, sourceRect, Color.White);
}
}
}
纹理的声明现在位于循环之外。