程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 圓和矩形相交,圓和矩形

圓和矩形相交,圓和矩形

編輯:C++入門知識

圓和矩形相交,圓和矩形


今天第一次寫博客,把今天自己寫的圓是否與矩形相交的程序記一記,自己使用Cocos2D-X寫游戲時,才想著寫出來的。

 

思路:1:先判斷圓心是否在矩形中

   2:判斷矩形四個點是否在圓中,如果矩形四個點不在圓中,可以排除圓心在矩形四個角區域外可能性。

   3:判斷圓是否和矩形的四個邊相交

 

程序代碼如下:

//用於判斷圓是否包含某個點

bool LeapCircle::containsPoint(const Point& pPoint) const {
  return (this->CircleOrigin.x-pPoint.x)*(this->CircleOrigin.x-pPoint.x)+(this->CircleOrigin.y-pPoint.y)*(this->CircleOrigin.y-pPoint.y) <= this->CircleRadius * this->CircleRadius;
}

//判斷圓是否和矩形相交

bool LeapCircle::intersectsRect(const Rect& rect) const {
  bool intersect1 = rect.containsPoint(this->CircleOrigin);                     //圓心在矩形內?
  bool intersect2 = this->containsPoint(Point(rect.getMinX(), rect.getMinY())) ||
            this->containsPoint(Point(rect.getMinX(), rect.getMaxY())) ||
            this->containsPoint(Point(rect.getMaxX(), rect.getMinY())) ||
            this->containsPoint(Point(rect.getMaxX(), rect.getMaxY()));          //矩形四個點是否在園內?
  bool intersect3 = this->CircleOrigin.x<rect.getMinX() && this->CircleOrigin.y>rect.getMinY() && this->CircleOrigin.y<rect.getMaxY() && abs(this->CircleOrigin.x-rect.getMinX()) < this->CircleRadius;  //是否和矩形左邊相交?
  bool intersect4 = this->CircleOrigin.x>rect.getMaxX() && this->CircleOrigin.y>rect.getMinY() && this->CircleOrigin.y<rect.getMaxY() && abs(this->CircleOrigin.x-rect.getMaxX()) < this->CircleRadius;  //是否和矩形右邊邊相交?
  bool intersect5 = this->CircleOrigin.y<rect.getMinY() && this->CircleOrigin.x>rect.getMinX() && this->CircleOrigin.x<rect.getMaxX() && abs(this->CircleOrigin.y-rect.getMinY()) < this->CircleRadius;  //是否和矩形下邊相交?
  bool intersect6 = this->CircleOrigin.x>rect.getMaxY() && this->CircleOrigin.x>rect.getMinX() && this->CircleOrigin.x<rect.getMaxX() && abs(this->CircleOrigin.y-rect.getMaxY()) < this->CircleRadius;  //是否和矩形上邊邊相交?
  

  return intersect1 || intersect2 || intersect3 || intersect4 || intersect5 || intersect6;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved