我正在使用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"来延迟这个方法。延迟(1000)。ContinueWith (t => snake)MoveForward());"但只在第一个循环中执行。当我调试时,蛇在第一个循环中成功延迟,但在其余循环中缩放。
我如何实现代码,使在每个循环的方法被延迟,使蛇可以在一个恒定的速度移动?
在循环的每次迭代中创建一个延迟的任务。你实际上并没有延迟循环,你只是延迟了MoveForward方法的执行,所以循环仍然以最大速度运行。这导致在初始延迟后,任务以与循环运行相同的速度执行。等待任务完成使用await
.
如果你想让蛇以一定的间隔移动,为什么不使用计时器呢?
Timer timer = new Timer(1000);
timer.AutoReset = true;
timer.Elapsed += ( sender, e ) => snake.MoveForward();
timer.Start();