这是我在我的 Android 应用程序中实现的游戏循环代码。
它工作得很好,但我遇到的问题是,虽然它将逻辑更新限制在 30 - 实际渲染运行平稳,这显然不利于电池寿命。
我不知道如何将渲染限制/上限为固定数量(比如 30 FPS 左右)。
具体来说,渲染应该只在逻辑已更新时渲染,而不是渲染冗余帧(即,当没有发生逻辑更新时)。
编辑:我刚刚添加了代码的插值部分 - 当我按照@Geobits 的建议限制帧时,这会导致问题吗?
int TICKS_PER_SECOND = 30;
int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
int MAX_FRAMESKIP = 10;
long next_game_tick = GetTickCount();
int loops;
bool game_is_running = true;
while( game_is_running ) {
loops = 0;
while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
update_game();
next_game_tick += SKIP_TICKS;
loops++;
}
interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
/ float( SKIP_TICKS );
display_game( interpolation );
}