简体   繁体   中英

Timer C# use in game development

I have a game in C# and I need to allow tournament mode in which each round will be of 2 minutes. How can I display the time from 0:00 up till 2:00 on the form?

I have this in a constructor:

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

And this is the Event Handler

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

but I don't know how I can begin the time from 0:00 instread of the current time.. I tried creating a DateTime instance but when I do myDateTime.ToString(); in the event handler, it just remains 0:00.

I tried searching but I can't find anything related. Thanks a lot !

Save current time to field when you are starting timer:

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

And calculate difference later:

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();
    }

You can store a DateTime.Now when you start the timer and then in every timer tick handler calculate how much time has passed between DateTime.Now and the stored start date. If you have a pause, you will need to also keep track of how long the game has been paused.

Considering the inconviniences with the above method, I would suggest you declare a StopWatch somewhere, instantiate and start it where you call timer.Start and then in your timer tick just read the Elapsed property of the StopWatch. You can even Stop and Start (pause) it if you need.

You need a member variable that is in scope for both the timer initialization and the Timer_Tick event handler.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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