FPS定时器不工作

时间:2017-03-26 10:34:20

标签: c++ sdl sdl-2

我使用c ++和sdl-2在Visual Studio 2015中创建游戏,我目前正在实施fps计时器,但它无法正常工作。基本的FPS定时器代码:

#include <SDL.h>
#include <Camera.h>

int main()
{

//create objects + camera

float frameTime = 0.0f;
int prevTime = 0;
int currentTime = 0;
float deltaTime = 0.0f;

    while (isRunning)
    {

    SDL_Event ev;

    keyState = SDL_GetKeyboardState(NULL);

    prevTime = currentTime;
    currentTime = SDL_GetTicks();
    deltaTime = (currentTime - prevTime) / 1000.0f;

    frameTime += deltaTime;

        if (frameTime >= 0.25f)
        {

            if (keyState[SDL_SCANCODE_W] && !FreeRoam)
            {
                Object1.GetPos().z = (Object2.GetPos().z + 1);
                camera.MoveForward(1);
            }
            //render
        }
    }

return 0;
}

有问题的FPS计时器是由CodingMadeEasy直接从this视频中删除的。问题是fps计时器就好像它不存在一样,所以我该如何解决这个问题呢?

2 个答案:

答案 0 :(得分:1)

看起来你在帧更新后没有将frameTime重置为0.

答案 1 :(得分:1)

阅读您的代码。你正在计算两行之间的时间:

prevTime = currentTime;
currentTime = SDL_GetTicks();
deltaTime = (currentTime - prevTime) / 1000.0f;

这没有任何意义。你想要两次循环迭代之间的时间,所以你必须在循环的边界中分割这些行:

while (isRunning)
{
    prevTime = currentTime; // Right here, in the loop's beguining

    SDL_Event ev;

    keyState = SDL_GetKeyboardState(NULL);

    if (frameTime >= 0.25f)
    {

        if (keyState[SDL_SCANCODE_W] && !FreeRoam)
        {
            Object1.GetPos().z = (Object2.GetPos().z + 1);
            camera.MoveForward(1);
        }
        //render
    }

    //End of the loop

    currentTime = SDL_GetTicks();
    deltaTime = (currentTime - prevTime) / 1000.0f;

    frameTime += deltaTime;
}