我需要在 sdl窗口上定义矩形区域,以便在特定区域点击鼠标按钮时,必须执行一些操作。
我使用GetMouseState(x,y)
来获取鼠标点击事件。它适用于单击鼠标按钮的任何位置。但我需要获取鼠标x和y并使用sdl rect x和y检查它是否单击矩形。
答案 0 :(得分:1)
假设您创建了一个包含所需矩形的SDL_Rect
结构。当您获得鼠标单击的坐标时,将其与矩形坐标进行比较非常简单:
/* 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;
}
答案 1 :(得分:0)
版本较短。注意对宽度和高度使用严格的不等式。我也更喜欢可视化2个角,而不是2个间隔。
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);
}