- #include "iostream"
- #include "math.h"
- using namespace std;
-
- #define EPS 0.00001
-
- struct pointf
- {
- float x;
- float y;
-
- pointf()
- {
-
- }
- pointf(float m, float n) : x(m),y(n)
- {
- }
- };
-
- /**
- * @brief 求线段与圆的交点
- * @return 如果有交点返回true,否则返回false
- * @note 与圆可能存在两个交点,如果存在两个交点在ptInter1和ptInter2都为有效值,如果有一个交点,则ptInter2的值为
- * 无效值,此处为65536.0
- */
- bool LineInterCircle(
- const pointf ptStart, // 线段起点
- const pointf ptEnd, // 线段终点
- const pointf ptCenter, // 圆心坐标
- const float Radius,
- pointf& ptInter1,
- pointf& ptInter2)
- {
- ptInter1.x = ptInter2.x = 65536.0f;
- ptInter2.y = ptInter2.y = 65536.0f;
-
- float fDis = sqrt((ptEnd.x - ptStart.x) * (ptEnd.x - ptStart.x) + (ptEnd.y - ptStart.y) * (ptEnd.y - ptStart.y));
-
- pointf d;
- d.x = (ptEnd.x - ptStart.x) / fDis;
- d.y = (ptEnd.y - ptStart.y) / fDis;
-
- pointf E;
- E.x = ptCenter.x - ptStart.x;
- E.y = ptCenter.y - ptStart.y;
-
- float a = E.x * d.x + E.y * d.y;
- float a2 = a * a;
-
- float e2 = E.x * E.x + E.y * E.y;
-
- float r2 = Radius * Radius;
-
- if ((r2 - e2 + a2) < 0)
- {
- return false;
- }
- else
- {
- float f = sqrt(r2 - e2 + a2);
-
- float t = a - f;
-
- if( ((t - 0.0) > - EPS) && (t - fDis) < EPS)
- {
- ptInter1.x = ptStart.x + t * d.x;
- ptInter1.y = ptStart.y + t * d.y;
- }
-
- t = a + f;
-
- if( ((t - 0.0) > - EPS) && (t - fDis) < EPS)
- {
- ptInter2.x = ptStart.x + t * d.x;
- ptInter2.y = ptStart.y + t * d.y;
- }
-
- return true;
- }
- }
-
- void main(void)
- {
- pointf ptStart(3.0, 2.0);
- pointf ptEnd(10.0, 6.0);
-
- pointf ptCenter(10.0, 4.0);
- float fR = 3.0;
-
- pointf pt1, pt2;
-
- if (!LineInterCircle(ptStart, ptEnd, ptCenter, fR, pt1, pt2))
- {
- cout<<"不相交!"<<endl;
- }
- else
- {
- cout<<"交点"<<endl;
- cout<<pt1.x<<" "<<pt1.y<<endl;
-
- cout<<pt2.x<<" "<<pt2.y<<endl;
- }
-
- }
|