【问题标题】:How to implement thread to add a timer to my game?如何实现线程以向我的游戏添加计时器?
【发布时间】:2016-12-02 17:30:50
【问题描述】:

我为游戏编写了 MVP。但现在我想给它加一个秒表,这样玩家就可以在游戏的左下角或右下角看到倒计时的时间。这不是关于如何创建这样一个秒表的问题,而是关于如何将它包含在我的游戏中的问题。

我已经想出了如何将时钟数字渲染到屏幕上,但问题是当我使用任何输入来触发时钟时,游戏仍然卡在时钟循环中。下面是一些代码来解释:

// when the player makes her first input the clock is triggered

if (!CLOCK)
    this->clockStatus(ON);


// within the clockStatus function
void Game::clockStatus(TimerState Status)
{
    do {                             /* Infinite Loop */
        t2->getTimefromSeconds(getCurrentSysTime());
        break;
    } while (1);
    while (1) {                        /* Another infinite loop */
        t_inter->getTimefromSeconds(getCurrentSysTime());
        t1 = (Timer*)(t_inter - t2);
    }
}

t1 的输出通过以下方式显示:

t1.display();

为了清楚起见,TimeState 是一个管理秒表状态的枚举。(ON/OFF)Timer 是实际的秒表类。

经过研究,我得出结论,当玩家第一次输入游戏时,会触发秒表,我应该为此创建一个新线程。这样主函数可以正常运行,辅助线程可以计算游戏时间。我可以阅读有关如何实现此功能的任何教程或pdf或练习吗?也欢迎所有有用的建议。

【问题讨论】:

  • 推测在这种情况下您需要threads,您已经成功了一半。了解您使用哪种平台进行显示/渲染会很有帮助。例如,如果您使用 Qt,您可以轻松使用 Qt 的 Timer 类。它的小部件显示系统是多线程的。
  • 什么是Timert1t2t_inter是什么类型?
  • 我正在使用 OpenGL 和 GLFW。但我想用 C++ 写秒表
  • 测量时间,您可以使用C++'s standard library。要显示它,只需评估每一帧的差异。不需要无限循环。也没有线程。
  • 秒表必须显示正在增加的时间。也许你可以写一些示例代码?

标签: c++ multithreading


【解决方案1】:

据我了解,您希望能够启动秒表,然后显示自启动以来经过的时间。最简单的方法是存储开始时间,然后(在您的正常渲染循环中)找到与当前时间的差异。你可以使用这个辅助类:

#include <chrono>

inline auto currentTime() {
    return std::chrono::high_resolution_clock::now();
}

struct Timer {
    Timer() { reset(); }
    void reset() { // reset the stopwatch to 0
        startTime = currentTime();
    }
    double getElapsed() { // get the elapsed time (in seconds)
        return std::chrono::duration_cast<std::chrono::nanoseconds>(
                  currentTime() - startTime
               ).count() / 1000000000.0;
    }
    std::chrono::time_point<std::chrono::steady_clock> startTime;
};

示例用法:

// global
Timer stopwatch;

// when the player does first input (or whenever)
stopwatch.reset();

// in your loop
double stopwatchSeconds = stopwatch.getElapsed();
// display the value...

【讨论】:

  • 谢谢 qxz,经过一些修改,您的示例运行良好!
  • @MagnusHimmler 如果它解决了您的问题,请不要忘记接受 qxz 的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2020-04-28
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多