2016-11-08 29 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

感謝您的幫助!你的方法奏效了。蛇現在不斷移動,並且可以朝各個方向移動。 –