版權聲明:本文為博主原創文章,未經博主允許不得轉載。https://www.cnblogs.com/baosong/p/9545040.html
其中需要傳入的四個點分別為:進行判斷的點和三角形的三個頂點
其中第一種方法和第二個方法都是通過三角形的特性進行判定
具體的原理大家可以揣摩一下,但是代碼可以進行使用
#region 用於判斷一個點是否在三角形范圍內 //向其中傳入四個點 public bool IsINTriangle(Vector3 point, Vector3 v0, Vector3 v1, Vector3 v2) { float x = point.x; float y = point.y; float v0x = v0.x; float v0y = v0.y; float v1x = v1.x; float v1y = v1.y; float v2x = v2.x; float v2y = v2.y; //第一種方法 //if (isInside(v0x, v0y, v1x, v1y, v2x, v2y, x, y)) // return true; //return false; //第二個方法 if ((pointInTriangle(v0x, v0y, v1x, v1y, v2x, v2y, x, y))) return true; return false; } //第一種檢測方法: double area(float x1, float y1, float x2,float y2, float x3, float y3) { return Math.Abs((x1 * (y2 - y3) +x2 * (y3 - y1) +x3 * (y1 - y2)) / 2.0); } bool isInside(float x1, float y1, float x2, float y2, float x3, float y3,float x, float y) { /* Calculate area of triangle ABC */ double A = area(x1, y1, x2, y2, x3, y3); /* Calculate area of triangle PBC */ double A1 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PAC */ double A2 = area(x1, y1, x, y, x3, y3); /* Calculate area of triangle PAB */ double A3 = area(x1, y1, x2, y2, x, y); /* Check if sum of A1, A2 and A3 is same as A */ return (A == A1 + A2 + A3); } //第二種檢測方法: bool pointInTriangle(float x1, float y1, float x2, float y2, float x3, float y3, float x, float y) { float denominator = ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3)); float a = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / denominator; float b = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / denominator; float c = 1 - a - b; return 0 <= a && a <= 1 && 0 <= b && b <= 1 && 0 <= c && c <= 1; } #endregion
以上就是判斷一個點是否在三角形中的兩種方式,大家可以選擇自己喜歡的方式和特定的情況進行選擇,希望能幫助到大家,大家有不懂得或者我錯的,歡迎在下方評論區進行評論,大家一起學習,謝謝!!!!!