【发布时间】:2016-11-08 17:32:31
【问题描述】:
我正在使用 SwinGame 开发一个蛇游戏。方法 MoveForward 处理蛇的移动。我现在遇到的问题是我无法延迟该特定方法,以便蛇以恒定的慢速移动。
这是 Main 中的代码:
using System;
using SwinGameSDK;
using System.Threading.Tasks;
namespace MyGame
{
public class GameMain
{
public static void Main ()
{
//Open the game window
SwinGame.OpenGraphicsWindow ("GameMain", 800, 600);
SwinGame.ShowSwinGameSplashScreen ();
Snake snake = new Snake ();
//Run the game loop
while (false == SwinGame.WindowCloseRequested ()) {
//Fetch the next batch of UI interaction
SwinGame.ProcessEvents ();
//Clear the screen and draw the framerate
SwinGame.ClearScreen (Color.White);
SwinGame.DrawFramerate (0, 0);
// Has to go after ClearScreen and NOT before refreshscreen
snake.Draw ();
Task.Delay (1000).ContinueWith (t => snake.MoveForward ());
snake.HandleSnakeInput ();
//Draw onto the screen
SwinGame.RefreshScreen (60);
}
}
}
}
从代码中可以看出,游戏在 while 循环中运行。我能够使用“Task.Delay (1000).ContinueWith (t => snake.MoveForward ());”来延迟该方法但仅限于第一个循环。当我调试时,蛇在第一个循环上成功延迟,但缩放超过了其余的循环。
如何实现代码,以便在每个循环中延迟该方法,以便蛇可以匀速移动?
提前致谢。
【问题讨论】:
-
您在循环内清除并重绘屏幕?这似乎不对
-
创建一个函数并从
ContinueWith递归调用它,而不是一个while循环。或者只是在ContinueWith之后添加Wait()来等待任务的结果 -
没有理由使用
Task.Delay。使用System.Timers.Timer。将蛇移动到回调内部。也不需要while循环 -
游戏循环设计有两种主要方法:(1) 测量每次循环迭代的时间增量,并根据经过的时间更新运动。 (2)在每次迭代中同步时间点。您的方法(3)假设每次迭代的时间是一些非常古老的游戏无法玩的原因,因为计算时间和等待时间之间的关系通常是不可预测的。 (ofc。当前的游戏编程中可能还有其他方法 - 我不是完全最新的)