Building SDL2 from a Subdirectory (CMake)

Enabling VSync with SDL2

How can I enable vertical synchronization (VSync) in my SDL2 application to prevent screen tearing?

Vector illustration representing computer programming

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.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 27 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved