Reputation: 11
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.
Upvotes: 1
Views: 1895
Reputation: 682
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
Upvotes: 3
Reputation: 409384
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;
}
Upvotes: 1
Reputation: 394
Shorter version. Note the use of strict inequality for width and height. I also prefer to visualize the 2 corners, instead of as 2 intervals.
int in_rect(int x, int y, struct SDL_Rect *r) {
return (x >= r->x) && (y >= r->y) &&
(x < r->x + r->w) && (y < r->y + r->h);
}
Upvotes: 0