碰撞檢測算法:點和矩形碰撞、點和圓形碰撞、矩形碰撞、圓形碰撞


一,原理介紹

這回有點復雜,不過看懂了還是很好理解的。當然,我不敢保證這種算法在任何情況下都會起效果,如果有同學測試時,發現出現錯誤,請及時聯系我。

我們首先來建立一個以圓心為原點的坐標系:

然后要檢測碰撞就只有兩種情況了。

 

情況一,矩形全部都在一個象限內,如圖:

當然,圖中只是舉個例子,不一定是只在第二象限,任何一個象限都行,只要是矩形全在該象限。

這種情況比較好解決,首先,我們計算出矩形每個角的坐標,然后用勾股定律依次算出這個角到圓心的距離是否小於或者等於半徑。設這個角與圓心橫坐標之差為d1,縱坐標之差為d2,半徑為r,公式表達如下:

如果有一個角滿足要求說明產生碰撞,返回true。

但是有朋友懵了,怎么判斷矩形是不是在一個象限內呢?很簡單,只要判斷這個矩形左上角和右下角是否在同一個象限內就可以了。於是我們得寫個函數來實現判斷某兩個角是否在同一象限。

函數代碼如下:

 

[javascript]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. function isSameQuadrant(cood,objA,objB){  
  2.     var coodX = cood.x;  
  3.     var coodY = cood.y;  
  4.     var xoA = objA.x  
  5.     ,yoA = objA.y  
  6.     ,xoB = objB.x  
  7.     ,yoB = objB.y;  
  8.       
  9.     if(xoA-coodX>0 && xoB-coodX>0){  
  10.         if((yoA-coodY>0 && yoB-coodY>0) || (yoA-coodY<0 && yoB-coodY<0)){  
  11.             return true;  
  12.         }  
  13.         return false;  
  14.     }else if(xoA-coodX<0 && xoB-coodX<0){  
  15.         if((yoA-coodY>0 && yoB-coodY>0) || (yoA-coodY<0 && yoB-coodY<0)){  
  16.             return true;  
  17.         }  
  18.         return false;  
  19.     }else{  
  20.         return false;  
  21.     }  
  22. }  

這個函數原本是准備寫到lufylegend中LMath靜態類中的,參數原本是LPoint對象,但是這里可以用json,因為LPoint里的x,y屬性可以寫到json里,函數也就同樣取得出值了。函數參數介紹:[cood創建的坐標系原點坐標, objA第一個點坐標, objB第二個點坐標] 這幾個參數均為json對象,格式為:

 

 

[javascript]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. {x:點的x坐標, y:點的y坐標}  

函數中的代碼還是很好理解的,就是判斷一下兩個點的x坐標都分別減去原點x坐標,看得出的數正負符號是否相同,然后又用同樣的辦法算出y軸上的符號是否相同,如果都相同就在同一象限。

 

有了這個函數,剩下得就好辦了,直接代入開頭給出的公式進行計算即可。

 

情況二,矩形跨度兩個象限或者兩個象限以上

這種情況更好辦,我們就可以直接把圓看作一個邊長為2r正方形,然后用矩形碰撞算法檢測正方形和矩形的碰撞,如下圖所示:

矩形碰撞的算法是什么呢?很easy,如圖:

如果要橫向判斷碰撞的話,判斷(x1-x2)的絕對值是否小於或者等於w1/2+w2/2,如果是則橫向則有碰撞。縱向判斷是一樣的,判斷(y1-y2)的絕對值是否小於或等於h1/2+h2/2即可。

有了這些算法,我們就可以實現情況2了。

 

二,Javascript版算法&測試代碼

先上代碼吧:

 

[javascript]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. function hitTestRectArc(rectObj,arcObj,rectVec,arcR){  
  2.     var rw = rectObj.getWidth()  
  3.     ,rh = rectObj.getHeight()  
  4.     ,ar = arcObj.getWidth()*0.5  
  5.     ,rx = rectObj.x  
  6.     ,ry = rectObj.y  
  7.     ,ax = arcObj.x  
  8.     ,ay = arcObj.y;  
  9.       
  10.     if(typeof rectVec != UNDEFINED){  
  11.         rx += (rw - rectVec[0])*0.5;  
  12.         ry += (rh - rectVec[1])*0.5;  
  13.         rw = rectVec[0];  
  14.         rh = rectVec[1];  
  15.     }  
  16.     if(typeof arcR != UNDEFINED){  
  17.         ax += (ar - arcR);  
  18.         ay += (ar - arcR);  
  19.         ar = arcR;  
  20.     }  
  21.       
  22.     var rcx = rx+rw*0.5,rcy = ry+rh*0.5;  
  23.     var rltx = rx  
  24.     ,rlty = ry  
  25.     ,rlbx = rx  
  26.     ,rlby = ry+rh  
  27.     ,rrtx = rx+rw  
  28.     ,rrty = ry  
  29.     ,rrbx = rx+rw  
  30.     ,rrby = ry+rh;  
  31.       
  32.     if(  
  33.         isSameQuadrant(  
  34.             {x:ax,y:ay},  
  35.             {x:rltx,y:rlty},  
  36.             {x:rrbx,y:rrby}  
  37.         )  
  38.     ){  
  39.         var dX1 = Math.abs(ax-rltx),dY1 = Math.abs(ay-rlty);  
  40.         var dX2 = Math.abs(ax-rlbx),dY2 = Math.abs(ay-rlby);  
  41.         var dX3 = Math.abs(ax-rrtx),dY3 = Math.abs(ay-rrty);  
  42.         var dX4 = Math.abs(ax-rrbx),dY4 = Math.abs(ay-rrby);  
  43.           
  44.         if(  
  45.             (((dX1*dX1) + (dY1*dY1)) <= (ar*ar))  
  46.             ||(((dX2*dX2) + (dY2*dY2)) <= (ar*ar))  
  47.             ||(((dX3*dX3) + (dY3*dY3)) <= (ar*ar))  
  48.             ||(((dX4*dX4) + (dY4*dY4)) <= (ar*ar))  
  49.         ){  
  50.             return true;  
  51.         }  
  52.         return false;  
  53.     }else{  
  54.         var result = false;  
  55.         var squareX = ax  
  56.         ,squareY = ay  
  57.         ,squareW = ar*2  
  58.         ,squareH = squareW;  
  59.         if(  
  60.             (Math.abs(squareX-rcx) <= (squareW+rw)*0.5)  
  61.             &&(Math.abs(squareY-rcy) <= (squareH+rh)*0.5)  
  62.         ){  
  63.             result = true;  
  64.         }  
  65.         return result;  
  66.     }  
  67. }  

 

由於是為lufylegend設計的函數,所以參數為 [ rectObj矩形對象(LSprite或者LShape對象), arcObj圓形對象(LSprite或者LShape對象), rectVec矩形規定大小(可不填), arcR圓形半徑(可不填)] 當然,或許些朋友不懂這幾行代碼:

 

 

[javascript]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. var rw = rectObj.getWidth()  
  2. ,rh = rectObj.getHeight()  
  3. ,ar = arcObj.getWidth()*0.5  
  4. ,rx = rectObj.x  
  5. ,ry = rectObj.y  
  6. ,ax = arcObj.x  
  7. ,ay = arcObj.y;  

好吧,我告訴你,這里用到的是lufylegend中LSprite和LShape,這兩個類有x、y屬性,還有獲取寬度和高度的getWidth()和getHeight(),這里看不懂沒關系,你知道是取高度和寬度還有x,y坐標的就行了。當然你要深究,那就看看lufylegend.js的API文檔吧:http://lufylegend.com/lufylegend/api ,以下測試代碼也用到了lufylegend.js,據說這個引擎是個不錯的引擎,想了解的同學,去官方網站看看吧:http://lufylegend.com/lufylegend/ 或者看看我的文章,大多數是講解有關lufylegend開發的。

 

示例代碼:

 

[javascript]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. init(50,"mylegend",500,250,main);  
  2.   
  3. function main(){  
  4.     LGlobal.setDebug(true);  
  5.                   
  6.     var back = new LSprite();  
  7.     back.graphics.drawRect(5,"green",[0,0,LStage.width,LStage.height],true,"lightblue");  
  8.     addChild(back);  
  9.       
  10.     var cObj = new LSprite();  
  11.     cObj.x = 200;  
  12.     cObj.y = 120;  
  13.     cObj.graphics.drawArc(0,"",[0,0,50,0,2*Math.PI],true,"red");  
  14.     back.addChild(cObj);  
  15.       
  16.     var rObj = new LSprite();  
  17.     rObj.x = 250;  
  18.     rObj.y = 70;  
  19.     rObj.alpha = 0.8;  
  20.     rObj.graphics.drawRect(0,"",[0,0,100,100],true,"green");  
  21.     back.addChild(rObj);  
  22.   
  23.     trace(hitTestRectArc(rObj,cObj));  
  24.       
  25.     back.addEventListener(LMouseEvent.MOUSE_DOWN,function(e){  
  26.         rObj.x = e.offsetX-rObj.getWidth()*0.5;  
  27.         rObj.y = e.offsetY-rObj.getHeight()*0.5;  
  28.         trace(hitTestRectArc(rObj,cObj));  
  29.     });  
  30. }  

測試鏈接:http://www.cnblogs.com/yorhom/articles/hitTestRectArc.html

 

 

三,C++版

 

C++版我用的是Qt,所以大家運行要在Qt creator里編譯運行。

HitTestAlg.h里的代碼:

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #ifndef HITTESTALG_H  
  2. #define HITTESTALG_H  
  3.   
  4. #include <math.h>  
  5. #include <QPoint>  
  6. #include <QRect>  
  7.   
  8. class CMath  
  9. {  
  10.   
  11. public:  
  12.   
  13.     static int pow(int base, int powerOf)  
  14.     {  
  15.         return (int)::pow((double)base, (double)powerOf);  
  16.     }  
  17.   
  18.     static int sqrt(int n)  
  19.     {  
  20.         return (int)::sqrt((double)n);  
  21.     }  
  22.   
  23.     static int abs(int n)  
  24.     {  
  25.         n = n < 0 ? -n : n;  
  26.         return n;  
  27.     }  
  28.   
  29.     static int distance(const QPoint& pt1, const QPoint& pt2)  
  30.     {  
  31.         return CMath::sqrt(CMath::pow(CMath::abs(pt1.x() - pt2.x()), 2) + CMath::pow(CMath::abs(pt1.y() - pt2.y()), 2));  
  32.     }  
  33.   
  34. };  
  35.   
  36. class CArc  
  37. {  
  38.   
  39. protected:  
  40.   
  41.     int m_nRadius;  
  42.     QPoint  m_ptCenter;  
  43.   
  44. public:  
  45.   
  46.     CArc() : m_nRadius(0), m_ptCenter(0, 0){}  
  47.     CArc(const CArc& arc) : m_nRadius(arc.radius()), m_ptCenter(arc.center()){}  
  48.     CArc(int radius, QPoint center) : m_nRadius(radius), m_ptCenter(center){}  
  49.     CArc(int radius, int centerX, int centerY) : m_nRadius(radius), m_ptCenter(centerX, centerY){}  
  50.     ~CArc(){}  
  51.   
  52.     void setRadius(int radius){m_nRadius = radius;}  
  53.     int radius() const {return m_nRadius;}  
  54.     void setCenter(const QPoint& center){m_ptCenter = center;}  
  55.     void setCenter(int centerX, int centerY){m_ptCenter = QPoint(centerX, centerY);}  
  56.     QPoint center() const {return m_ptCenter;}  
  57.     QRect rect() const {return QRect(center().x() - radius(), center().y() - radius(), 2 * radius(), 2 * radius());}  
  58.   
  59. };  
  60.   
  61. class CHitTestAlg  
  62. {  
  63.   
  64. protected:  
  65.   
  66.     QRect   m_rtRect;  
  67.     CArc    m_arArc;  
  68.   
  69. protected:  
  70.   
  71.     bool locatedSameQuadrant() const  
  72.     {  
  73.         bool bRes = false;  
  74.         int nRectLeft = m_rtRect.left(), nRectTop = m_rtRect.top(), nRectRight = m_rtRect.right(), nRectBottom = m_rtRect.bottom();  
  75.         int nArcCenterX = m_arArc.center().x(), nArcCenterY = m_arArc.center().y();  
  76.         if((nRectLeft - nArcCenterX >= 0 && nRectRight - nArcCenterX >= 0 && nRectTop - nArcCenterY <= 0 && nRectBottom - nArcCenterY <= 0)  
  77.             || (nRectLeft - nArcCenterX <= 0 && nRectRight - nArcCenterX <= 0 && nRectTop - nArcCenterY <= 0 && nRectBottom - nArcCenterY <= 0)  
  78.             || (nRectLeft - nArcCenterX <= 0 && nRectRight - nArcCenterX <= 0 && nRectTop - nArcCenterY >= 0 && nRectBottom - nArcCenterY >= 0)  
  79.             || (nRectLeft - nArcCenterX >= 0 && nRectRight - nArcCenterX >= 0 && nRectTop - nArcCenterY >= 0 && nRectBottom - nArcCenterY >= 0)  
  80.         ){  
  81.             bRes = true;  
  82.         }  
  83.         return bRes;  
  84.     }  
  85.   
  86.     bool hitTestRect() const  
  87.     {  
  88.         QRect rtArc = m_arArc.rect();  
  89.         bool bRes = false;  
  90.         if(CMath::abs(m_rtRect.center().x() - rtArc.center().x()) <= CMath::abs((m_rtRect.width() + rtArc.width()) / 2)  
  91.             && CMath::abs(m_rtRect.center().y() - rtArc.center().y()) <= CMath::abs((m_rtRect.height() + rtArc.height()) / 2)  
  92.         ){  
  93.             bRes = true;  
  94.         }  
  95.         return bRes;  
  96.     }  
  97.   
  98.     bool hitTestAngleArc() const  
  99.     {  
  100.         bool bRes = false;  
  101.         QPoint ptRectTopLeft = m_rtRect.topLeft(), ptRectTopRight = m_rtRect.topRight()  
  102.         , ptRectBottomLeft = m_rtRect.bottomLeft(), ptRectBottomRight = m_rtRect.bottomRight()  
  103.         , ptArcCenter = m_arArc.center();  
  104.         int nArcRadius = m_arArc.radius();  
  105.   
  106.         if(CMath::distance(ptRectTopLeft, ptArcCenter) <= nArcRadius  
  107.             || CMath::distance(ptRectTopRight, ptArcCenter) <= nArcRadius  
  108.             || CMath::distance(ptRectBottomLeft, ptArcCenter) <= nArcRadius  
  109.             || CMath::distance(ptRectBottomRight, ptArcCenter) <= nArcRadius  
  110.         ){  
  111.             bRes = true;  
  112.         }  
  113.         return bRes;  
  114.     }  
  115.   
  116. public:  
  117.   
  118.     CHitTestAlg(const QRect& rect, const CArc& arc) : m_rtRect(rect), m_arArc(arc){}  
  119.     ~CHitTestAlg(){}  
  120.   
  121.     bool hitTest() const  
  122.     {  
  123.         bool bRes = false;  
  124.         if(locatedSameQuadrant()){  
  125.             bRes = hitTestAngleArc();  
  126.         }else{  
  127.             bRes = hitTestRect();  
  128.         }  
  129.         return bRes;  
  130.     }  
  131.   
  132. };  
  133.   
  134. #endif // HITTESTALG_H  

mainwindow.h里的代碼:

 

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #ifndef MAINWINDOW_H  
  2. #define MAINWINDOW_H  
  3.   
  4. #include <QWidget>  
  5. #include "HitTestAlg.h"  
  6.   
  7. class MainWindow : public QWidget  
  8. {  
  9.     Q_OBJECT  
  10.   
  11. protected:  
  12.   
  13.     QRect       m_rtRect;  
  14.     CArc        m_arArc;  
  15.     bool        m_bHit;  
  16.   
  17. protected:  
  18.   
  19.     virtual void mouseReleaseEvent(QMouseEvent *mouseEvent);  
  20.     virtual void paintEvent(QPaintEvent *paintEvent);  
  21.   
  22. public:  
  23.   
  24.     MainWindow(QWidget *parent = 0);  
  25.     ~MainWindow();  
  26.   
  27. };  
  28.   
  29. #endif // MAINWINDOW_H  

mainwindow.cpp里的代碼:

 

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #include <QDebug>  
  2. #include <QMouseEvent>  
  3. #include <QBrush>  
  4. #include <QPainter>  
  5. #include "mainwindow.h"  
  6.   
  7. MainWindow::MainWindow(QWidget *parent)  
  8.     : QWidget(parent)  
  9.     , m_rtRect(0, 0, 100, 50)  
  10.     , m_arArc(50, 200, 200)  
  11.     , m_bHit(false)  
  12. {  
  13.     QWidget::showMaximized();  
  14. }  
  15.   
  16. MainWindow::~MainWindow()  
  17. {  
  18.       
  19. }  
  20.   
  21. void MainWindow::mouseReleaseEvent(QMouseEvent *mouseEvent)  
  22. {  
  23.     if(mouseEvent){  
  24.         QPoint ptPos = mouseEvent->pos();  
  25.         QRect rtRect;  
  26.         rtRect.setX(ptPos.x() - m_rtRect.width() / 2);  
  27.         rtRect.setY(ptPos.y() - m_rtRect.height() / 2);  
  28.         rtRect.setWidth(m_rtRect.width());  
  29.         rtRect.setHeight(m_rtRect.height());  
  30.         m_rtRect = rtRect;  
  31.         m_bHit = CHitTestAlg(m_rtRect, m_arArc).hitTest();  
  32.         QWidget::update();  
  33.     }  
  34. }  
  35.   
  36. void MainWindow::paintEvent(QPaintEvent *paintEvent)  
  37. {  
  38.     Q_UNUSED(paintEvent)  
  39.   
  40.     QPainter xPainter(this);  
  41.     {  
  42.     xPainter.save();  
  43.     QBrush xBrush; xBrush.setColor(Qt::red); xBrush.setStyle(Qt::SolidPattern);  
  44.     QPen xPen; xPen.setColor(Qt::black); xPen.setStyle(Qt::SolidLine);  
  45.     xPainter.setBrush(xBrush);  
  46.     xPainter.setPen(xPen);  
  47.     xPainter.drawEllipse(m_arArc.center(), m_arArc.radius(), m_arArc.radius());  
  48.     xPainter.restore();  
  49.     }  
  50.     {  
  51.     xPainter.save();  
  52.     QBrush xBrush; xBrush.setColor(Qt::darkGreen); xBrush.setStyle(Qt::SolidPattern);  
  53.     QPen xPen; xPen.setColor(Qt::black); xPen.setStyle(Qt::SolidLine);  
  54.     xPainter.setBrush(xBrush);  
  55.     xPainter.setPen(xPen);  
  56.     xPainter.drawRect(m_rtRect);  
  57.     xPainter.restore();  
  58.     }  
  59.     {  
  60.     xPainter.save();  
  61.     QString sContent = QString("Hit Test: %1").arg(m_bHit ? "true" : "false");  
  62.     QFont ftFont("Tahoma", 12, QFont::DemiBold, true);  
  63.     xPainter.setFont(ftFont);  
  64.     xPainter.drawText(20, m_arArc.rect().bottom() + 30, sContent);  
  65.     xPainter.restore();  
  66.     }  
  67. }  

main.cpp里的代碼:

 

 

[cpp]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. #include <QApplication>  
  2. #include "mainwindow.h"  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QApplication a(argc, argv);  
  7.     MainWindow w;  
  8.     w.show();  
  9.       
  10.     return a.exec();  
  11. }  

原理和js版是一樣的,就不多解釋了,在下面我會放出所有代碼。C++版運行demo如下:

 


Qt做的界面感覺還是不錯的,哈哈~~

 

 

 

 

點和矩形碰撞

 

[java]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
 
  1. /** 
  2.      *  
  3.      * @param x1 點 
  4.      * @param y1 點 
  5.      * @param x2 矩形view x 
  6.      * @param y2 矩形view y 
  7.      * @param w  矩形view 寬 
  8.      * @param h  矩形view 高 
  9.      * @return 
  10.      */  
  11.     public static boolean isCollsion(int x1, int y1, int x2, int y2, int w, int h) {  
  12.         if (x1 >= x2 && x1 <= x2 + w && y1 >= y2 && y1 <= y2 + h) {  
  13.             return true;  
  14.         }   
  15.         return false;  
  16.     }  


矩形碰撞

 

 

[java]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
 
  1. /** 
  2.      * 檢測兩個矩形是否碰撞 
  3.      * @return 
  4.      */  
  5.     public boolean isCollsionWithRect(int x1, int y1, int w1, int h1,   
  6.             int x2,int y2, int w2, int h2) {  
  7.         if (x1 >= x2 && x1 >= x2 + w2) {  
  8.             return false;  
  9.         } else if (x1 <= x2 && x1 + w1 <= x2) {  
  10.             return false;  
  11.         } else if (y1 >= y2 && y1 >= y2 + h2) {  
  12.             return false;  
  13.         } else if (y1 <= y2 && y1 + h1 <= y2) {  
  14.             return false;  
  15.         }  
  16.         return true;  
  17.     }  


點(x1,x2) , 圓心(x2,y2) ,半徑r

 

 

[java]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
 
  1. if (Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) <= r) {  
  2.             // 如果點和圓心距離小於或等於半徑則認為發生碰撞  
  3.             return true;  
  4.         }  

 

 

圓和圓

 

[java]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
 
    1. /** 
    2.      * 圓形碰撞 
    3.      *  
    4.      * @param x1 
    5.      *            圓形1的圓心X坐標 
    6.      * @param y1 
    7.      *            圓形2的圓心X坐標 
    8.      * @param x2 
    9.      *            圓形1的圓心Y坐標 
    10.      * @param y2 
    11.      *            圓形2的圓心Y坐標 
    12.      * @param r1 
    13.      *            圓形1的半徑 
    14.      * @param r2 
    15.      *            圓形2的半徑 
    16.      * @return 
    17.      */  
    18.     private boolean isCollisionWithCircle(int x1, int y1, int x2, int y2,  
    19.             int r1, int r2) {  
    20.         // Math.sqrt:開平方  
    21.         // Math.pow(double x, double y): X的Y次方  
    22.         //直角坐標系,依點1和點2做平行線,|x1-x2|為橫向直角邊,|y1-y2|為縱向直角邊 依勾股定理 c^2=a^2+b^2  
    23.         if (Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) <= r1 + r2) {  
    24.             // 如果兩圓的圓心距小於或等於兩圓半徑和則認為發生碰撞  
    25.             return true;  
    26.         }  
    27.         return false;  
    28.     }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM