我试图通过使用gettimeofday将我的游戏循环限制在一个特定的FPS上。这是一个非常初级的游戏,所以它一直在消耗我所有的处理能力。
无论我将FRAMES_PER_SECOND设置得多低,它都会继续尽可能快地运行。
我很好地掌握了deWiTTERS对游戏循环的看法,但我使用的是gettimeofday,而不是GetTickCount b/c。
另外,我运行的是OSX,使用的是C++,GLUT。
下面是我的main的样子:
int main (int argc, char **argv)
{
while (true)
{
timeval t1, t2;
double elapsedTime;
gettimeofday(&t1, NULL); // start timer
const int FRAMES_PER_SECOND = 30;
const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
double next_game_tick = elapsedTime;
int sleep_time = 0;
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize (windowWidth, windowHeight);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutIdleFunc (idle);
glutReshapeFunc (reshape);
glutPassiveMotionFunc(mouseMovement); //check for mouse movement
glutMouseFunc(buttonPress); //check for button press
gettimeofday(&t2, NULL); // stop timer after one full loop
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // compute sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // compute us to ms
next_game_tick += SKIP_TICKS;
sleep_time = next_game_tick - elapsedTime;
if( sleep_time >= 0 )
{
sleep( sleep_time );
}
glutMainLoop ();
}
}我已经尝试将gettimeofday和sleep函数放在多个位置,但似乎找不到适合它们的最佳位置(考虑到我的代码甚至是正确的)。
发布于 2012-07-12 03:59:49
它只会被调用一次。我相信你需要把FPS逻辑放在display函数中,因为glutMainLoop永远不会返回。(这也意味着不需要您的while循环。)
编辑:或者更可能的是,它应该放在你的空闲函数中。我已经有一段时间没有使用glut了。
发布于 2012-07-12 04:04:19
glutMainLoop()
glutMainLoop进入GLUT事件处理循环。此例程在GLUT程序中最多只能调用一次。一旦调用,此例程将永远不会返回。它将在必要时调用任何已注册的回调。
发布于 2012-07-12 04:04:33
在你从elapsed_time初始化next_game_tick的时候,你还没有初始化elapsed_time。
https://stackoverflow.com/questions/11440434
复制相似问题