如果2線傳遞給函數,怎麼可以推斷他們是否會相交?每行都以2個CPoint
對象的形式 - 總共有4個點。以下是我想到的。它計算每條線的斜率和Y軸截距,並從中計算出交點。然後檢查交點是否位於段上;如果是,則返回false;如果不是,即它們不相交,則返回true。 雖然,它顯示了很多問題。有沒有更簡單,更有效的方法來做到這一點?
注意:我不是很確定哪些數據類型用於斜率和Y軸截距。
bool CShortestPathFinderDoc::edgeTest(CPoint P,CPoint P2,CPoint E,CPoint E2)
{
bool status=true;
double m1,m2; //slopes
double b1,b2; //y-intercepts
double y,x; //intersection point
m1=((double)P.y-P2.y)/((double)P.x-P2.x);
m2=((double)E.y - E2.y)/((double)E.x - E2.x);
if(m1 == m2) //if lines are colinear
return true;
b1=P.y-(m1*P.x) // Get the..
b2=E->y - (m2*E.x); // Y-intercepts.
x=(b2-b1)/(m1-m2);
y=m1*x + b1; //x,y is the intersection point!!!
if((x<P2.x && x>P.x)) //if intersection point lies on line!!!!!
{
if(P2.y > P.y)
if(y<P2.y && y>P.y)
status=false;
if(P2.y < P.y)
if(y<P.y && y>P2.y)
status=false;
}
return status;
}