今天第一次寫博客,把今天自己寫的圓是否與矩形相交的程序記一記,自己使用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;
}