U_判断点是否在三角形内
参考链接:
https://leetcode-cn.com/circle/discuss/7OldE4/
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

浙公网安备 33010602011771号