2013-10-21 99 views
0

我正在用C++ OpenGL製作一個小遊戲。每當程序運行通過代碼時,update()通常被調用一次。我試圖限制每秒60次(我希望遊戲在不同速度的計算機上以相同的速度更新)。限制C++中的更新速率。爲什麼這個代碼每秒更新一次不是每秒60次?

下面的代碼運行一個計時器,一旦定時器大於0.0166666666666667(每秒60次),應該調用update()。然而,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>下面的答案中所提到的,沒有ms準確性。因此,我已實現了以下代碼具有正確的精度:

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

回答

2

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

Calculates the difference in seconds between beginning and end 

所以,你以秒爲單位。所以,即使你的值是double,你也會得到一個整數。

因此,當差異至少爲1秒時,您只會得到一個值和前一個值之間的差異。

+0

我不知道爲什麼函數返回'double','long'看起來更合適。 – SJuan76

+0

這很有道理。謝謝。有沒有另一種計算差異而不使用'difftime'的方法?我對這個計時器有點新鮮。 – user2779315

+0

我一直在環顧四周,看起來''不適合比一秒更精確。但是我知道有些圖書館可以提供更好的精確度。 – SJuan76