defining sdl_rect and sdl_mousebuttondown
I need to define rectangular areas on the sdl window so that when the mouse button is clicked on a particular area some action has to be performed.
I used GetMouseState(x,y)
to get the mouse click event. It works wherever the mouse button is clicked. But rather i need to get the mouse x and y and check it with sdl rect x and y to c if whether the rectangle is clicked.
Solution 1:
Lets say you create a SDL_Rect
structure containing the rectangle you want. When you get the coordinates of a mouse-click it's very simple to compare it with the rectangle coordinates:
/* Function to check if a coordinate (x, y) is inside a rectangle */
int check_click_in_rect(int x, int y, struct SDL_Rect *rect)
{
/* Check X coordinate is within rectangle range */
if (x >= rect->x && x < (rect->x + rect->w))
{
/* Check Y coordinate is within rectangle range */
if (y >= rect->y && y < (rect->y + rect->h))
{
/* X and Y is inside the rectangle */
return 1;
}
}
/* X or Y is outside the rectangle */
return 0;
}
Solution 2:
There actually is a built in function for that called SDL_PointInRect
. It returns true if clicked and false otherwise
It takes SDL_Point*
and SDL_Rect*
as arguments
SDL_Point mousePosition;
// Mouse click coords from event handler
mousePosition.x = event.motion.x;
mousePosition.y = event.motion.y;
if (SDL_PointInRect(&mousePosition, &someSDL_Rect) {
// Do something
}
If you look into the header file, this function is very similar to @Alink 's answer