(フレーム数の変化ではなく) 時間の変化に応じてゲームオブジェクトが動く仕組みを作ることができました。私は今、練習のために、FPS リミッターを課そうとしています。
私が抱えている問題は、予想よりも 2 倍の量のゲーム ループが発生していることです。たとえば、フレーム数を 1 FPS に制限しようとすると、その 1 秒間に 2 つのフレームが通過します。1 つの非常に長いフレーム (~1 秒) と 1 つの非常に短いフレーム (~15 ミリ秒) です。これは、各ゲーム ループ間の時間差 (ミリ秒単位) を出力することで確認できます。出力例は、993、17、993、16... のようになります。
FPS が制限される前にデルタ時間が計算されるようにコードを変更しようとしましたが、役に立ちませんでした。
タイマー クラス:
#include "Timer.h"
#include <SDL.h>
Timer::Timer(void)
{
_currentTicks = 0;
_previousTicks = 0;
_deltaTicks = 0;
_numberOfLoops = 0;
}
void Timer::LoopStart()
{
//Store the previous and current number of ticks and calculate the
//difference. If this is the first loop, then no time has passed (thus
//previous ticks == current ticks).
if (_numberOfLoops == 0)
_previousTicks = SDL_GetTicks();
else
_previousTicks = _currentTicks;
_currentTicks = SDL_GetTicks();
//Calculate the difference in time.
_deltaTicks = _currentTicks - _previousTicks;
//Increment the number of loops.
_numberOfLoops++;
}
void Timer::LimitFPS(int targetFps)
{
//If the framerate is too high, compute the amount of delay needed and
//delay.
if (_deltaTicks < (unsigned)(1000 / targetFps))
SDL_Delay((unsigned)(1000 / targetFps) - _deltaTicks);
}
(の一部) ゲーム ループ:
//The timer object.
Timer* _timer = new Timer();
//Start the game loop and continue.
while (true)
{
//Restart the timer.
_timer->LoopStart();
//Game logic omitted
//Limit the frames per second.
_timer->LimitFPS(1);
}
注: SMA を使用して FPS を計算しています。このコードは省略されています。