2016-11-08 28 views
0

我正在使用SwinGame开发蛇游戏。 MoveForward方法处理蛇的运动。我现在面临的问题是,我无法推迟这种特殊的方法,使蛇以恒定的低速运动。拖延蛇游戏的单一方法c#

下面是在主代码:

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())”来延迟方法;“但仅限于第一个循环。当我调试时,蛇在第一个循环中成功延迟,但是缩小了其余的循环。

我该如何实现代码,以便在每个循环中该方法被延迟以便蛇能够以恒定速度移动?

在此先感谢。

+1

你清除并重画屏幕内循环?这看起来不正确 –

+0

而不是一个while循环创建一个函数,并从'ContinueWith'递归调用它。或者只需在'ContinueWith'后面加上'Wait()'来等待任务的结果 –

+0

没有理由使用'Task.Delay'。使用'System.Timers.Timer'。移动蛇内部回调。不需要while循环 –

回答

2

您正在循环的每次迭代中创建延迟任务。你实际上并没有延迟循环,只是延迟了MoveForward方法的执行,所以循环仍然以最大速度运行。这会导致在初始延迟任务以与循环运行相同的速度执行之后。等待任务完成使用await

如果你想蛇以一定的时间间隔移动,为什么不使用计时器?

Timer timer = new Timer(1000); 
timer.AutoReset = true; 
timer.Elapsed += (sender, e) => snake.MoveForward(); 
timer.Start(); 
+0

实际上,定时器很好,但值得一提的是,他从来没有真正“等待”延迟的任务,那就是问题的根源。 – grek40

+0

这就是我的意思,虽然再次阅读答案,它不是很清楚。我编辑了答案,希望现在更清楚。 – EpicSam

+0

感谢您的帮助!你的方法奏效了。蛇现在不断移动,并且可以朝各个方向移动。 –