首页 > 解决方案 > 每 0.25 秒做一次

问题描述

以下函数连续运行:

void MyClass::handleTriggered(float dt)
{
    // dt is time interval (period) between current call to this function and previous one
}

dt类似于0.0166026秒(来自每秒 60 帧)。

我打算每秒钟做点什么0.25。目前我正在使用我们处于 60 fps 的事实,即函数调用每秒发生 60 次:

    static long int callCount = 0;
    ++callCount;
    // Since we are going with 60 fps, then 15 calls is 1/4 i.e. 0.25 seconds
    if (callCount % 15 == 0)
        // Do something every 0.25 seconds (every 15 calls)

现在我想知道如何以另一种方式做到这一点,使用float类型而不是int

    static float sumPeriod = 0.0;
    // Total time elapsed so far
    sumPeriod += dt;
    if (/* How to compose the condition? */) {
        // Every 0.25 seconds do something
    }

标签: c++

解决方案


你必须总结dt's,当它们达到 0.25 时,你从总和中减去 0.25 并做你的事情。

static float sum = 0.0;
sum += dt;
if(sum > 0.25) {
    sum -= 0.25;
    // Do what you want to do every 0.25 secs here.
}

推荐阅读