【问题标题】:Delay a single method for snake game c#延迟蛇游戏c#的单一方法
【发布时间】: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。当前的游戏编程中可能还有其他方法 - 我不是完全最新的)

标签: c# xamarin


【解决方案1】:

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

如果您希望蛇以特定间隔移动,为什么不使用计时器?

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

【讨论】:

  • 其实定时器很好,但值得一提的是,他实际上从来没有awaits延迟任务,这就是问题的根源。
  • 这就是我的意思,尽管再次阅读答案并不是很清楚。我编辑了答案,希望现在更清楚。
  • 感谢您的帮助!你的方法奏效了。蛇现在不停地移动,罐子向各个方向移动。
猜你喜欢
  • 2011-11-26
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2014-07-24
  • 2023-03-19
  • 2019-10-09
  • 1970-01-01
  • 2015-06-30
相关资源
最近更新 更多