关于判断两个矩阵相交的一点想法

今天在阅读chipmunk2D源码时,在cpBB.h中看到了一个判读矩阵相交的函数

static inline cpBool cpBBIntersects(const cpBB a, const cpBB b)
{
    return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
}

将其转换为熟悉的c++代码后:

typedef struct{
    double     l;      //left
    double     b;     //bottom
    double     r;     //right
    double     t;    //top
} CRect;

bool CRectIntersects(const CRect a, const CRect b){
    return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
}    

两个矩阵相交,两个矩阵的必定部分叠在一起,将两个矩阵的left,bottom,top,right互相限制就行,上面函数就是两个矩阵互相限制。

另一个方法就是从反面考虑,考虑什么情况下矩阵不相交,代码如下:

bool  CRectIntersects(const CRect a, const CRect  b){
  return !(a.r < b.l || a.r > b.l || a.t < b.b || a.b > b.t);          
}

还有一种方法就是根据两个矩阵相交形成的矩阵判断,

两个矩阵相交的结果一定是一个矩阵,构成相交矩阵为CRect{newLeft,newBottom,newRight,newTop}

newLeft      = max(a.l,b.l)
newBottom    = max(a.t,b.t)
newRight     = min(a.r,b.r)
newTop       = min(a.t,b.t)

如果矩阵a与b不相交的话,则newLeft > newRight || newBottom > newTop,故判断相交的函数为

bool  CRectIntersect(const CRect a, const CRect b){
     newLeft        = max(a.l,b.l);
    newBottom    = max(a.t,b.t);
    newRight       = min(a.r,b.r);
    newTop         = min(a.t,b.t);  
    return !(newLeft > newRight || newBottom > newTop)      
}

 

 

 

posted @ 2013-11-19 11:55  OpenSoucre  阅读(2278)  评论(0编辑  收藏  举报