C++ visualc&x2B+;直线碰撞

C++ visualc&x2B+;直线碰撞,c++,visual-studio-2010,collision-detection,C++,Visual Studio 2010,Collision Detection,几天前,我刚刚开始使用Win32 GUI编程。我正在尝试做一个简单的游戏,我需要检测两个物体之间的碰撞。 因此,我使用RECTstruct制作了我的角色 为了检测它们是否发生碰撞,我使用了: // 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 &&

几天前,我刚刚开始使用Win32 GUI编程。我正在尝试做一个简单的游戏,我需要检测两个物体之间的碰撞。 因此,我使用
RECT
struct制作了我的角色

为了检测它们是否发生碰撞,我使用了:

// 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;
}
//如果点(x,y)位于矩形内,则返回1,否则返回0
int是矩形中的点(RECT r,int x,int y){
如果((r.left=x)&&
(右下=y)
返回1;
返回0;
}
//如果矩形重叠,则返回1,否则返回0
int do_矩形相交(矩形a,矩形b){
if(是矩形中的点(a、b、左、b、上)||
是矩形中的点(a、b、右、b、上)||
是矩形中的点(a,b.左,b.下)||
是矩形中的点(a、b、右、b、下))
返回1;
if(是矩形中的点(b,a.左,a.顶)||
是矩形中的点(b,a.右,a.顶)||
是矩形中的点(b,a.左,a.下)||
是矩形中的点(b,a.右,a.下))
返回1;
返回0;
}
这是我在这里的一个问题上发现的,它似乎适用于这样的情况。但是在这种情况下有一个小问题

有没有办法解决这个问题?我做错了吗?我应该尝试另一种方法吗?
任何提示都会有所帮助。

看看API函数:

  • -“如果矩形相交,则返回值为非零。”

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

清楚地检查一个矩形的角是否在另一个矩形内是个坏主意:

进行检查的简单方法是:

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

   // No intersection

} else {

   // Intersection

}

if(a.left>=b.right | | a.right=b.bottom | | | a.bottom谢谢你,我最后在我最初使用的函数末尾添加了这个函数,它似乎完成了任务。该代码完成了整个检查,它可以完全替换该函数。试着用纸和笔花一些时间来理解为什么它对所有可能的情况都足够了。在那张图片中n4个条件中的一个似乎满足了,因此报告了一个交叉点(它应该是这样的)。我当然假设left您可以为这些值命名吗?例如,如果它们是
(左,上)-(右,下)
对于第一对和第二对,这意味着
top>bottom
。是的,L,tr,B它不返回交点,并且它们明显相交(-1,0),(1,-2)(0,1),(2,-1)