判斷平面上一點是否在三角形內 Inside a triangle or not

平面內有一個三角形,三個頂點ABC的座標已經給出。現在給出一個座標點K,要求判斷這個點是在三角形內部還是外部。注意在三角形的三邊上也算是在內部。

方法:

1、面積法

點K和三角形三頂點中的任意兩點組合成三個不同的三角形,KAB、KBC、KAC,判斷這三個三角形的面積之和是否等原三角的面積。如果相等的話,說明是在內部。

2、射線法

從K作水平向左射線,如果K在三角形內部,那麼這條射線與三角形的交點個數必爲奇數;如果P在外部,則交點個數必爲偶數。

3、矢量法

由A點逆時針沿着三角形的邊走一圈回到A,這一過程中若點K始終在前進方向的左側,那麼K在內部;否則是在外部。


方法一的實現:

根據三角形三點座標求面積的公式:abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0)

float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
   return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
 
/* 根據三角形的三點座標和點K的座標判斷 
   A(x1, y1), B(x2, y2) and C(x3, y3) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{   
   /* Calculate area of triangle ABC */
   float A = area (x1, y1, x2, y2, x3, y3);
 
   /* Calculate area of triangle PBC */  
   float A1 = area (x, y, x2, y2, x3, y3);
 
   /* Calculate area of triangle PAC */  
   float A2 = area (x1, y1, x, y, x3, y3);
 
   /* Calculate area of triangle PAB */   
   float A3 = area (x1, y1, x2, y2, x, y);
   
   return (A == A1 + A2 + A3);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章