To enable VSync in SDL2, you need to set the SDL_RENDERER_PRESENTVSYNC
flag when creating your renderer. Here's an example:
#include <SDL.h>
int main(int argc, char** argv) {
SDL_Window* window{SDL_CreateWindow(
"VSync Example",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600, SDL_WINDOW_SHOWN
)};
SDL_Renderer* renderer{SDL_CreateRenderer(
window, -1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC
)};
// Game loop
// ...
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
The SDL_RENDERER_PRESENTVSYNC
flag tells SDL to synchronize screen updates with the refresh rate of the monitor. This eliminates screen tearing by ensuring that frames are only updated during the vertical blanking interval.
Keep in mind that enabling VSync will limit your application's frame rate to the refresh rate of the monitor (typically 60 FPS). If your game runs faster than this, you may want to consider using a frame limiter to prevent excessive CPUÂ usage.
Answers to questions are automatically generated and may not have been reviewed.
A step-by-step guide on setting up SDL2 and useful extensions in a project that uses CMake as its build system