В настоящее время у меня есть что-то близкое к следующей реализации независимого игрового цикла 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
}
}
}