Creating the Main Loop with SDL2

Capturing Mouse Events in SDL2

What is the best way to handle mouse events in an SDL2 application?

Abstract art representing computer programming

Handling mouse events in SDL2 involves checking for SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, and SDL_MOUSEMOTION events within your event loop. Here’s how to capture and respond to these events:

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

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Window* window = SDL_CreateWindow(
    "Mouse Event Example", 100, 100, 640, 480, 0);
  SDL_Renderer* renderer = SDL_CreateRenderer(
    window, -1, SDL_RENDERER_ACCELERATED);

  bool running = true;
  SDL_Event event;
  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) running = false;
      if (event.type == SDL_MOUSEBUTTONDOWN) {
        std::cout << "Mouse button pressed at ("
          << event.button.x << ", "
          << event.button.y << ")\n";
      }
      if (event.type == SDL_MOUSEBUTTONUP) {
        std::cout << "Mouse button released at ("
          << event.button.x << ", "
          << event.button.y << ")\n";
      }
      if (event.type == SDL_MOUSEMOTION) {
        std::cout << "Mouse moved to ("
          << event.motion.x << ", "
          << event.motion.y << ")\n";
      }
    }

    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);
  }

  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
Mouse button pressed at (434, 257)
Mouse moved to (434, 258)
Mouse moved to (429, 260)
Mouse moved to (415, 266)
Mouse button released at (415, 266)

This example demonstrates handling various mouse events, including button presses, releases, and mouse movement, providing feedback on the console regarding the mouse's position and actions.

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:

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