int CApp::OnExecute()
{
// Initialize application.
int state = OnInit();
if (state != APP_OK) {
return state;
}
// Enter the SDL event loop.
SDL_Event event;
running = true;
fps = true;
static int last_time = 0;
static int real_FPS;
static int good_FPS;
int show_fps_flag = 0;
while (running)
{
while (SDL_PollEvent(&event)) {
OnEvent(&event);
}
if (SDL_GetTicks() - last_time != 0)
{
real_FPS = 1000 / (SDL_GetTicks() - last_time);
good_FPS = real_FPS / 20 + good_FPS * 19 / 20;
}
else
{
real_FPS = 1000;
good_FPS = 50 + good_FPS * 19 / 20;
}
if(real_FPS <= FPS)
{
last_time = SDL_GetTicks();
if (fps == true)
{
if(real_FPS != 0)
{
if(show_fps_flag++ * 10 / real_FPS != 0)
{
printf("FPS:%d\n", good_FPS);
show_fps_flag = 0;
}
}
else
{
printf("FPS:%d\n", good_FPS);
show_fps_flag = 0;
}
}
OnUpdate();
OnRender();
}
}
return state;
}
对事件操作不限制FPS,对Update和Rander每帧更新。
本来想显示在窗口左上角,无奈SDL扩展库ttf还没有弄清楚如何在 osX 上实现,暂时先显示在输出端。
由于都是用 int 计算,所以真·FPS的数值分布是1000,500,333,250,200,166......非常难受,所以我使用了均值抹匀了FPS,使其看起来不会跳得太快,又因为每帧都显示看起来太瞎眼,所以设定为每10帧显示一次。
防止除数为零,做了if else判断。