2013-03-21 129 views
1

我刚刚开始使用Win32 GUI编程,几天前。我试图做一个简单的游戏,我需要检测两个对象之间的碰撞。 所以我用RECT结构visual C++ 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

有没有什么办法解决这个问题?我做错了吗?我应该尝试一种不同的方法吗? 任何提示将有所帮助。

回答

1

显然检查,如果一个长方形的角落里,另一个是一个坏主意:

Intersecting rectangles

一个简单的方法做检查,而不是:

if (a.left >= b.right || a.right <= b.left || 
    a.top >= b.bottom || a.bottom <= b.top) { 

    // No intersection 

} else { 

    // Intersection 

} 
+0

谢谢你,我结束了在我最初使用的函数的末尾加上这个,并且它似乎完成了这项工作 – 2013-03-21 15:18:08

+0

这段代码完成了整个检查,它可以完全替代**该函数。试着花一些时间用纸和铅笔来理解为什么它足以应付所有可能的情况。 – 6502 2013-03-21 15:34:38

+0

我只是测试它,它似乎并没有在这种情况下工作http://puu.sh/2lrXw – 2013-03-21 17:25:35

0

此解决方案无效。你可能有两个矩形相交,而没有任何一个顶点位于另一个顶点。例如((0,0), (10,10))((5,-5), (7, 15))。尝试检查其中一个矩形的是否与另一个矩形相交。