Time Delay Error

I have a mistake in my logic and it’s hard for me to understand what it is. Basically, I constantly calculate the time interval of each iteration of the game loop and add this duration to the duration before it. I am trying to calculate the total playing time. Of course, this does not give the correct results. What am I doing wrong? Any recommendations are appreciated.

        private TimeSpan totalDuration = TimeSpan.FromSeconds(1);
        private int score = 0;

        public void Stop()
        {
            IsGameOver = true;
            //MessageBox.Show(String.Format("Game Over\n\nScore = {0}", score));
            MessageBox.Show(String.Format("Game Over\n\nScore = {0}\n\nTime
            Duration={1}", score, totalDuration));
            Application.Exit();
        }

        public void Start()
        {

            score = 0;
            IsGameOver = false;

            currentRedLightX = 0;
            currentRedLightY = 0;

            currentGreenLightX = width / 2;
            currentGreenLightY = height / 2;


            double minIterationDuration = SPEED; // 50 frames / sec

            //game loop
            while (!IsGameOver)
        {
            if (IsCollision())
            {
                score += 10;
            }

            DateTime startIterationTime = System.DateTime.UtcNow;
            UpdateGameState();
            Render();
            DateTime endIterationTime = System.DateTime.UtcNow;
            TimeSpan iterationDuration = endIterationTime - startIterationTime;
            totalDuration += iterationDuration;
            //totalDuration += iterationDuration.Duration();                
            if (iterationDuration.TotalMilliseconds < minIterationDuration)
                Thread.Sleep(Convert.ToInt32(minIterationDuration - 
                iterationDuration.TotalMilliseconds));

            Application.DoEvents();
        }
+3
source share
4 answers

You do not include in due time everything that happens in your call DoEvents, so you will not record all the time of the game.

If everything you do shows the total duration, why not just use the start and end times for the game, instead of summing up all the tiny intervals between them?

+1

StopWatch :

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Do stuff ...
stopWatch.Stop();
+5

DateTime.UtcNow . , , , , iterationDuration , . , Stopwatch ( , Start/Stop , Reset) . Stopwatch , .

, Application.DoEvents . , Timer...

+1

I assume that you are lacking in your logic to take into account the time when you send the thread to sleep. You might want to add this time before or after sending it to sleep.

+1
source

Source: https://habr.com/ru/post/1777083/


All Articles