Calculating the distance of the mouse cursor from the edges of the SDL window is straightforward. You need to know the current position of the mouse cursor and the dimensions of the window.
Here’s a complete example demonstrating how to calculate the distance of the mouse cursor from the edges of the window:
#include <SDL.h>
#include <iostream>
void CalculateMouseDistances(
int mouseX, int mouseY,
int windowWidth, int windowHeight
) {
int distanceFromLeft = mouseX;
int distanceFromTop = mouseY;
int distanceFromRight = windowWidth - mouseX;
int distanceFromBottom = windowHeight - mouseY;
std::cout << "Distance from left: "
<< distanceFromLeft << '\n';
std::cout << "Distance from top: "
<< distanceFromTop << '\n';
std::cout << "Distance from right: "
<< distanceFromRight << '\n';
std::cout << "Distance from bottom: "
<< distanceFromBottom << '\n';
}
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "SDL_Init Error: "
<< SDL_GetError() << '\n';
return 1;
}
SDL_Window* window = SDL_CreateWindow(
"Mouse Distance Calculation",
100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (window == nullptr) {
std::cerr << "SDL_CreateWindow Error: "
<< SDL_GetError() << '\n';
SDL_Quit();
return 1;
}
int windowWidth, windowHeight;
SDL_GetWindowSize(
window, &windowWidth, &windowHeight);
SDL_Event event;
bool running = true;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
} else if (event.type == SDL_MOUSEMOTION) {
int mouseX = event.motion.x;
int mouseY = event.motion.y;
CalculateMouseDistances(
mouseX, mouseY,
windowWidth, windowHeight
);
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Distance from left: 100
Distance from top: 150
Distance from right: 540
Distance from bottom: 330
SDL_GetWindowSize()
retrieves the width and height of the window.SDL_MOUSEMOTION
events to get the current position of the mouse cursor.CalculateMouseDistances()
function computes the distances from the mouse cursor to each edge of the window using simple arithmetic.mouseX
mouseY
windowWidth - mouseX
windowHeight - mouseY
By combining the current mouse position with the window dimensions, you can easily calculate the distance from the mouse cursor to any edge of the window.
This technique is useful for implementing features like edge scrolling or snapping UI elements to window edges.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to detect and handle mouse input events in SDL, including mouse motion, button clicks, and window entry/exit.