SDL provides two main ways to get mouse coordinates through SDL_GetMouseState()
and SDL_GetGlobalMouseState()
. The key difference lies in their frame of reference and typical use cases.
Relative coordinates are reported by SDL_GetMouseState()
and are measured relative to the top-left corner of your window. These coordinates start at (0,0) at your window's top-left corner and increase as you move right and down. They're most useful when you need to:
Here's an example showing how to use relative coordinates:
#include <SDL.h>
#include <iostream>
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window =
SDL_CreateWindow("Relative Coordinates",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600,
SDL_WINDOW_SHOWN);
bool running = true;
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
int x, y;
SDL_GetMouseState(&x, &y);
// Check if mouse is in top-left quadrant
if (x < 400 && y < 300) {
std::cout <<
"Mouse in top-left quadrant at "
<< x << "," << y << "\n";
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Global coordinates are reported by SDL_GetGlobalMouseState()
and are measured relative to the top-left corner of the primary display. These coordinates can be negative in multi-monitor setups. They're most useful when you need to:
Here's an example demonstrating global coordinates:
#include <SDL.h>
#include <iostream>
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
// Create two windows side by side
SDL_Window* window1 =
SDL_CreateWindow("Window 1", 100, 100, 400,
300, SDL_WINDOW_SHOWN);
SDL_Window* window2 =
SDL_CreateWindow("Window 2", 550, 100, 400,
300, SDL_WINDOW_SHOWN);
bool running = true;
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
int globalX, globalY;
SDL_GetGlobalMouseState(&globalX, &globalY);
std::cout << "Mouse at global position: "
<< globalX << "," << globalY << "\n";
}
SDL_DestroyWindow(window1);
SDL_DestroyWindow(window2);
SDL_Quit();
return 0;
}
When choosing between relative and global coordinates, consider your specific needs:
Answers to questions are automatically generated and may not have been reviewed.
Learn how to track mouse movements and button states across your entire application, even when the mouse leaves your window.