Relative Mouse Mode

SDL2 vs SDL3 Relative Mode

How does relative mode work differently in SDL2 vs. SDL3?

Abstract art representing computer programming

SDL3 introduces several important changes to relative mouse mode handling. Here's a comprehensive comparison of the differences:

// SDL2 Version
#include <SDL.h>
#include "Window.h"

class SDL2MouseHandler {
 public:
  bool Initialize(SDL_Window* Window) {
    // SDL2: Global relative mode
    return SDL_SetRelativeMouseMode(SDL_TRUE) == 0;
  }
};
// SDL3 Version
#include <SDL3/SDL.h>
#include "Window.h"

class SDL3MouseHandler {
 public:
  bool Initialize(SDL_Window* Window) {
    // SDL3: Window-specific relative mode
    return SDL_SetWindowRelativeMouseMode(
      Window, SDL_TRUE) == 0;
  }
};

Key differences include:

  • SDL3 uses window-specific relative mode instead of global
  • SDL3 provides better multi-window support
  • SDL3 adds new configuration options
  • SDL3 improves error handling and reporting

Here's a more detailed example showing how to write code that works with both versions:

#include <SDL.h>
#include <iostream>

#ifdef SDL_MAJOR_VERSION
#if SDL_MAJOR_VERSION >= 3
#define SDL3_MODE
#endif
#endif

class PortableMouseHandler {
public:
  bool Initialize(SDL_Window* Window) {
#ifdef SDL3_MODE
    if (SDL_SetWindowRelativeMouseMode(
      Window, SDL_TRUE) < 0
    ) {
      std::cout << "SDL3: Failed to enable "
                << "relative mode\n";
      return false;
    }
#else
    if (SDL_SetRelativeMouseMode(SDL_TRUE)
      < 0) {
      std::cout << "SDL2: Failed to enable "
                << "relative mode\n";
      return false;
    }
#endif
    return true;
  }

  void Cleanup(SDL_Window* Window) {
#ifdef SDL3_MODE
    SDL_SetWindowRelativeMouseMode(
      Window, SDL_FALSE);
#else
    SDL_SetRelativeMouseMode(SDL_FALSE);
#endif
  }
};

The main considerations when migrating from SDL2 to SDL3 are:

  • Update function calls to use window-specific variants
  • Review error handling as error codes may differ
  • Test multi-window scenarios if applicable
  • Update any custom relative mode management code
  • Review documentation for new SDL3 features and hints

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:

  • 62 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