0

我正在用 C++ OpenGL 制作一个小游戏。update()通常在程序每次运行代码时调用一次。我试图将其限制为每秒 60 次(我希望游戏在不同速度的计算机上以相同的速度更新)。

下面包含的代码运行一个计时器,update()一旦计时器 >= 0.0166666666666667(每秒 60 次),就应该调用它。然而,该语句if((seconds - lastTime) >= 0.0166666666666667)似乎每秒只触发一次。有谁知道为什么?

在此先感谢您的帮助。

//Global Timer variables
double secondsS;
double lastTime;
time_t timer;
struct tm y2k;
double seconds;

void init()
{
    glClearColor(0,0,0,0.0);                        // Sets the clear colour to white.
                                                    // glClear(GL_COLOR_BUFFER_BIT) in the display function

    //Init viewport
    viewportX = 0;
    viewportY = 0;

    initShips();

    //Time
    lastTime = 0;
    time_t timerS;
    struct tm y2k;
    y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
    y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;
    time(&timerS);  /* get current time; same as: timer = time(NULL)  */
    secondsS = difftime(timerS,mktime(&y2k));
    printf ("%.f seconds since January 1, 2000 in the current timezone \n", secondsS);

    loadTextures();
    ShowCursor(true);

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

}

void timeKeeper()
{
    y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
    y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;

    time(&timer);  /* get current time; same as: timer = time(NULL)  */

    seconds = difftime(timer,mktime(&y2k));
    seconds -= secondsS; 

    //Run 60 times a second. This limits updates to a constant standard.
    if((seconds - lastTime) >= 0.0166666666666667)
    {
        lastTime = seconds;

        update();

        //printf ("%.f seconds since beginning program \n", seconds);
    }
}

timeKeeper()在 int 中调用WINAPI WinMain,而程序是!done

编辑:

感谢那些提供帮助的人,您为我指明了正确的轨道。正如下面的答案中提到的那样<ctime>,没有毫秒精度。因此,我实现了以下具有正确准确性的代码:

double GetSystemTimeSample()
{
    FILETIME ft1, ft2;
    // assume little endian and that ULONGLONG has same alignment as FILETIME
    ULONGLONG &t1 = *reinterpret_cast<ULONGLONG*>(&ft1),
              &t2 = *reinterpret_cast<ULONGLONG*>(&ft2);

    GetSystemTimeAsFileTime(&ft1);
    do
    {
        GetSystemTimeAsFileTime(&ft2);
    } while (t1 == t2);

    return (t2 - t1) / 10000.0;
}//GetSystemTimeSample

void timeKeeper()
{
    thisTime += GetSystemTimeSample();
    cout << thisTime << endl;

    //Run 60 times a second. This limits updates to a constant standard.
    if(thisTime >= 16.666666666666699825) //Compare to a value in milliseconds
    {
        thisTime = seconds;

        update();
    }
}
4

1 回答 1

2

http://www.cplusplus.com/reference/ctime/difftime/

Calculates the difference in seconds between beginning and end

所以,你会在几秒钟内得到一个值。所以,即使你的值是double,你也会得到一个整数。

因此,只有当差异至少为 1 秒时,您才会得到一个值与前一个值之间的差异。

于 2013-10-21T11:40:07.633 回答