gpt4 book ai didi

c++ - 在 C++ 中限制更新速率。为什么这段代码每秒更新一次而不是每秒更新 60 次?

转载 作者:行者123 更新时间:2023-11-28 03:06:44 25 4
gpt4 key购买 nike

我正在用 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();
}
}

最佳答案

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

Calculates the difference in seconds between beginning and end

因此,您可以在几秒钟内获得一个值。因此,即使您的值为 double,您也会得到一个整数。

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

关于c++ - 在 C++ 中限制更新速率。为什么这段代码每秒更新一次而不是每秒更新 60 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19493450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com