几天前,我刚刚开始使用 Win32 GUI 编程。我正在尝试制作一个简单的游戏,我需要在其中检测两个物体之间的碰撞。
所以我使用 RECT
结构
为了检测它们是否发生碰撞,我使用了:
// Returns 1 if the point (x, y) lies within the rectangle, 0 otherwise
int is_point_in_rectangle(RECT r, int x, int y) {
if ((r.left <= x && r.right >= x) &&
(r.bottom <= y && r.top >= y))
return 1;
return 0;
}
// Returns 1 if the rectangles overlap, 0 otherwise
int do_rectangles_intersect(RECT a, RECT b) {
if ( is_point_in_rectangle(a, b.left , b.top ) ||
is_point_in_rectangle(a, b.right, b.top ) ||
is_point_in_rectangle(a, b.left , b.bottom) ||
is_point_in_rectangle(a, b.right, b.bottom))
return 1;
if ( is_point_in_rectangle(b, a.left , a.top ) ||
is_point_in_rectangle(b, a.right, a.top ) ||
is_point_in_rectangle(b, a.left , a.bottom) ||
is_point_in_rectangle(b, a.right, a.bottom))
return 1;
return 0;
}
这是我在这里的一个问题上发现的,它似乎适用于 this 这样的情况。 .但是这种情况有一个小问题here
有什么办法可以解决吗?我做错了吗?我应该尝试不同的方法吗? 任何提示都会有所帮助。
最佳答案
很明显,检查一个矩形的角是否在另一个矩形内部是个坏主意:
一个简单的检查方法是:
if (a.left >= b.right || a.right <= b.left ||
a.top >= b.bottom || a.bottom <= b.top) {
// No intersection
} else {
// Intersection
}
关于c++ - 视觉 C++ RECT 碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550879/