【问题标题】:Unable to create smooth animation in SDL 2无法在 SDL 2 中创建流畅的动画
【发布时间】:2019-04-16 01:11:46
【问题描述】:

我在 SDL 2 中遇到动画问题。我尝试了两种可能的解决方案来限制帧速率: 一个使用 16 毫秒的恒定睡眠(仅用于测试),另一个使用计时器以实现更准确的帧上限(runGameLoop_computed 游戏循环功能)。 出于测试目的,我只是使用 SDL_RenderFillRect 函数绘制和移动一个矩形,但是这两种游戏循环方法都会在矩形的移动中产生抖动。

你知道这里出了什么问题,动画不流畅吗?

完整的代码是这样的:

#include <iostream>
#include <SDL.h>
#include <chrono>
#include <thread>
#include <math.h>

using namespace std;

//sdl window and window renderer pointers
static SDL_Window *gWindow;
static SDL_Renderer *windowRenderer;

//terminates the app when users closes the window
static bool exitAppFlag = false;

static int window_width = 1000;
static double position_x = 0; // current x position to draw the rectangle
static double delta_time = 0; // the time passed since last draw


//initilizes SDL and displays the application window
void initSDL()
{
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
    }
    else
    {
        printf( "SDL ok \n");

        //Create window
        gWindow = SDL_CreateWindow( "Tank Multiplayer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, 500, SDL_WINDOW_SHOWN);

        if( gWindow == nullptr )
        {
            printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
        }
        else
        {
            //Create renderer for window
            windowRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED);
            //windowRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_SOFTWARE);

            if(windowRenderer == nullptr )
            {
                printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
            }
            else
            {
                //Initialize renderer color
                SDL_SetRenderDrawColor(windowRenderer, 0, 0, 255, 255);
                //SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x00 );
            }
        } //SDL_CreateWindow

    }
}

//part of game loop: processes events (currently handles only window close event)
void processEvents()
{
    SDL_Event p_event;
    while (SDL_PollEvent(&p_event) != 0){
        if (p_event.type == SDL_EventType::SDL_QUIT){
            //if the user closed the window, then set the flag to true, so that we can exit the application
            exitAppFlag = true;
            return;
        }
    }

}

//part of game loop: updates the position_x variable based on the time passed since the last time (delta_time)
void update()
{
    static double speed = 0.0532;
    position_x += delta_time * speed;
    if (position_x > window_width) position_x = 0;
}

//part of game loop: draws the rectange to the screen
void draw()
{
    SDL_Rect r;
    r.h = 300;
    r.w = 100;
    r.x = static_cast<int>(round(position_x));
    r.y = 0;
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x00 );
    SDL_RenderClear(windowRenderer);
    SDL_SetRenderDrawColor(windowRenderer, 0, 0, 255, 255);
    SDL_RenderFillRect(windowRenderer, &r);
    SDL_RenderPresent(windowRenderer);
}

//game loop: frame capping based on the given fps
void runGameLoop_computed()
{
    static double fps = 60;
    static double single_frame_time_micro = (1000 / fps) * 1000;
    std::chrono::time_point<std::chrono::high_resolution_clock>begin_time_point = std::chrono::high_resolution_clock::now();//stores the time point before processing game objects and drawing
    long long delta_time_micro = 0;

    while (!exitAppFlag) {
        delta_time_micro  = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - begin_time_point).count();
        if (delta_time_micro < single_frame_time_micro){
            std::this_thread::sleep_for(std::chrono::microseconds(static_cast<long long>(single_frame_time_micro - delta_time_micro)));
            delta_time_micro = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - begin_time_point).count();
        }
        delta_time = delta_time_micro / 1000.00;
        //std::cout <<  delta_time << std::endl;

        begin_time_point = std::chrono::high_resolution_clock::now();//stores the time point before processing game objects and drawing

        processEvents();
        update();
        draw();
    }
}

//game loop: constant sleep time 16 ms, almost 60fps
void runGameLoop_static()
{
    delta_time = 16.0;
    while (!exitAppFlag) {
        SDL_Delay(16);

        processEvents();
        update();
        draw();
    }
}

int main()
{
    //initilize SDL library and create window
    initSDL();

    //enter game loop
    //runGameLoop_static(); //constant sleep time 16ms
    runGameLoop_computed(); //frame capping based on given fps

    return 0;
}

在 main 函数中,您可以取消注释 witch 方法来测试: runGameLoop_static 要么 runGameLoop_computed

我在这里上传了完整的 Qt 项目(macOS):https://www.sendspace.com/file/1p4oqq

【问题讨论】:

  • 拍打SDL_RENDERER_PRESENTVSYNC 并使用runGameLoop_computed() 而不使用sleep_for()
  • 还可以尝试使用std::floor()/std::ceil() 而不是std::round() 进行矩形位置整数转换。
  • 另外,您要返回哪种渲染器? OpenGL 后端还是 Metal?
  • @genpfault 看起来 SDL_RENDERER_PRESENTVSYNC 改进了很多。我将对其进行测试,看看它是否在所有地方都受支持,因为我在某处读过它不支持。
  • @genpfault 我得到 4 个渲染驱动程序:opengl、opengles2、metal、software

标签: c++ macos animation sdl-2 game-loop


【解决方案1】:

我不确定这是否会解决抖动问题(它可能会),但您可以通过睡眠直到一个时间点来提高达到目标 60 帧/秒的准确度,而不是睡一段时间。这使您的循环逻辑更简单,让您无需计算处理每一帧所需的时间。

void
runGameLoop_computed()
{
    using FrameDuration = std::chrono::duration<int, std::ratio<1, 60>>;
    auto next_start = std::chrono::steady_clock::now() + FrameDuration{1};

    while (!exitAppFlag)
    {
        processEvents();
        update();
        draw();

        std::this_thread::sleep_until(next_start);
        next_start += FrameDuration{1};
    }
}

【讨论】:

  • @howad-hinnant 感谢您的回复。我通过添加增量时间尝试了您的解决方案,但看起来使用 SDL 获得平滑动画的唯一方法是使用 SDL_RENDERER_PRESENTVSYNC,即使那样也不是 100% 平滑。仍在研究如何做到这一点。
猜你喜欢
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 2012-01-13
相关资源
最近更新 更多