我目前有一个接近以下实现的物理游戏独立于FPS的循环。在我测试过的几乎每台计算机上都能很好地工作,当帧速率下降时保持游戏速度一致。然而,我将要将其移植到嵌入式设备上,这些设备很可能会更难处理视频,因此我想知道它是否仍然能够胜任。
编辑:
对于这个问题,请假设msecs()返回程序运行的毫秒数。 msecs的实现因不同平台而异。此循环在不同平台上也以不同方式运行。
#define MSECS_PER_STEP 20
int stepCount, stepSize; // these are not globals in the real source
void loop() {
int i,j;
int iterations =0;
static int accumulator; // the accumulator holds extra msecs
static int lastMsec;
int deltatime = msec() - lastMsec;
lastMsec = msec();
// deltatime should be the time since the last call to loop
if (deltatime != 0) {
// iterations determines the number of steps which are needed
iterations = deltatime/MSECS_PER_STEP;
// save any left over millisecs in the accumulator
accumulator += deltatime%MSECS_PER_STEP;
}
// when the accumulator has gained enough msecs for a step...
while (accumulator >= MSECS_PER_STEP) {
iterations++;
accumulator -= MSECS_PER_STEP;
}
handleInput(); // gathers user input from an event queue
for (j=0; j<iterations; j++) {
// here step count is a way of taking a more granular step
// without effecting the overall speed of the simulation (step size)
for (i=0; i<stepCount; i++) {
doStep(stepSize/(float) stepCount); // forwards the sim
}
}
}