我目前对基于物理的游戏的 FPS 独立游戏循环的以下实现接近。它在我测试过的几乎每台计算机上都运行良好,在帧速率下降时保持游戏速度一致。然而,我将移植到嵌入式设备,这可能会在视频方面更加困难,我想知道它是否仍然会减少芥末。
编辑:
对于这个问题,假设 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
}
}
}