Capturing Mouse Events in SDL2
What is the best way to handle mouse events in an SDL2 application?
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.
Implementing an Application Loop
Step-by-step guide on creating the SDL2 application and event loops for interactive games