Unity检测一个点是否在三角形区域里边的两种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。https://www.cnblogs.com/baosong/p/9538111.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

以上就是判断一个点是否在三角形中的两种方式,大家可以选择自己喜欢的方式和特定的情况进行选择,希望能帮助到大家,大家有不懂得或者我错的,欢迎在下方评论区进行评论,大家一起学习,谢谢!!!!!

文章转自:https://www.cnblogs.com/baosong/p/9538111.html

猜你喜欢

转载自www.cnblogs.com/baosong/p/9545040.html