繁体   English   中英

Timer C#用于游戏开发

[英]Timer C# use in game development

我有一个C#游戏,我需要允许比赛模式,其中每轮将是2分钟。 如何在表格上显示从0:00到2:00的时间?

我在构造函数中有这个:

        Timer timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += new EventHandler(Timer_Tick);
        timer.Start();

这就是事件处理程序

    void Timer_Tick(object sender, EventArgs e)
    {
        this.textBox1.Text = DateTime.Now.ToLongTimeString();
    }

但我不知道如何从当前时间的0:00开始的时间开始..我尝试创建一个DateTime实例但是当我做myDateTime.ToString(); 在事件处理程序中,它只是0:00。

我试过搜索,但找不到任何相关内容。 非常感谢 !

在启动计时器时将当前时间保存到字段:

_startTime = DateTime.Now;
timer.Start();

然后计算差异:

void Timer_Tick(object sender, EventArgs e)
{
    this.textBox1.Text = (DateTime.Now - _startTime).ToString(@"mm\:ss");
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value. 
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);

void Timer_Tick(object sender, EventArgs e)
    {
        label1.Text = stopWatch.ElapsedTicks.ToString();
    }

您可以在启动计时器时存储DateTime.Now,然后在每个计时器滴答处理程序中计算DateTime.Now与存储的开始日期之间经过的时间。 如果你有暂停,你还需要跟踪游戏暂停的时间。

考虑到上述方法的不便之处,我建议你在某个地方声明一个StopWatch ,实例化并在你调用timer.Start的地方启动它,然后在你的计时器中,只需读取StopWatch的Elapsed属性。 如果需要,您甚至可以停止和启动(暂停)它。

您需要一个成员变量,它在定时器初始化和Timer_Tick事件处理程序的作用域内。

class Something
{
    DateTime _myDateTime;
    Timer _timer;

    public Something()
    {
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Tick += Timer_Tick;

        _myDateTime = DateTime.Now;
        _timer.Start();

    }

    void Timer_Tick(object sender, EventArgs e)
    {
        var diff = DateTime.Now.Subtract(_myDateTime);
        this.textBox1.Text = diff.ToString();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM