判断点是否在多边形中的方法

这2个都只适用于不考虑y的情况

public static bool IsPointInPolygon(Vector2 point, IReadOnlyList polygon)
    {
        int polygonLength = polygon.Count, i = 0;
        bool inside = false;

        float pointX = point.x, pointY = point.y;
        float startX, startY, endX, endY;

        Vector2 endPoint = polygon[polygonLength - 1];
        endX = endPoint.x;
        endY = endPoint.y;

        while (i < polygonLength)
        {
            startX = endX;
            startY = endY;
            endPoint = polygon[i++];
            endX = endPoint.x;
            endY = endPoint.y;
            inside ^= (endY > pointY ^ startY > pointY) &&
                      ((pointX - endX) < (pointY - endY) * (startX - endX) / (startY - endY));
        }

        return inside;
    }
/// 
    /// 计算一个点是否在一个多边形范围内,没有考虑y的影响
    /// 如果过该点的线段与多边形的交点不为零且距该点左右方向交点数量都为奇数时  该点再多边形范围内
    /// 
    /// 测试点
    /// 多边形的顶点集合
    /// 
    public static bool PolygonIsContainPoint(Vector3 point, List vertexs)
    {
        //判断测试点和横坐标方向与多边形的边的交叉点

        int leftNum = 0; //左方向上的交叉点数
        int rightNum = 0; //右方向上的交叉点数
        int index = 1;

        for (int i = 0; i < vertexs.Count; i++)
        {
            if (i == vertexs.Count - 1)
            {
                index = -i;
            }

            //找到相交的线段 
            if (point.z >= vertexs[i].z && point.z < vertexs[i + index].z ||
                point.z < vertexs[i].z && point.z >= vertexs[i + index].z)
            {
                Vector3 vecNor = (vertexs[i + index] - vertexs[i]);
                
                //处理直线方程为常数的情况
                if (vecNor.x == 0.0f)
                {
                    if (vertexs[i].x < point.x)
                    {
                        leftNum++;
                    }
                    else if (vertexs[i].x == point.x)
                    {
                    }
                    else
                    {
                        rightNum++;
                    }
                }
                else
                {
                    vecNor = vecNor.normalized;
                    float k = vecNor.z / vecNor.x;
                    float b = vertexs[i].z - k * vertexs[i].x;

                    if ((point.z - b) / k < point.x)
                    {
                        leftNum++;
                    }
                    else if ((point.z - b) / k == point.x)
                    {
                    }
                    else
                    {
                        rightNum++;
                    }
                }
            }
        }

        if (leftNum % 2 != 0 || rightNum % 2 != 0)
        {
            return true;
        }

        return false;
    }

你可能感兴趣的:(Unity)