Example #1
0
    //The list describing the polygon has to be sorted either clockwise or counter-clockwise because we have to identify its edges
    public static bool ContainsPoint(List <Vector2> polygonPoints, Vector2 point)
    {
        //Step 1. Find a point outside of the polygon
        //Pick a point with a x position larger than the polygons max x position, which is always outside
        Vector2 maxXPosVertex = polygonPoints[0];

        for (int i = 1; i < polygonPoints.Count; i++)
        {
            if (polygonPoints[i].x > maxXPosVertex.x)
            {
                maxXPosVertex = polygonPoints[i];
            }
        }

        //The point should be outside so just pick a number to make it outside
        Vector2 pointOutside = maxXPosVertex + new Vector2(10f, 0f);

        //Step 2. Create an edge between the point we want to test with the point thats outside
        Vector2 l1_p1 = point;
        Vector2 l1_p2 = pointOutside;

        //Step 3. Find out how many edges of the polygon this edge is intersecting
        int numberOfIntersections = 0;

        for (int i = 0; i < polygonPoints.Count; i++)
        {
            //Line 2
            Vector2 l2_p1 = polygonPoints[i];

            int iPlusOne = ClampListIndex(i + 1, polygonPoints.Count);

            Vector2 l2_p2 = polygonPoints[iPlusOne];

            //Are the lines intersecting?
            if (Lines.AreLinesIntersecting(l1_p1, l1_p2, l2_p1, l2_p2, true))
            {
                numberOfIntersections += 1;
            }
        }

        //Step 4. Is the point inside or outside?
        bool isInside = true;

        //The point is outside the polygon if number of intersections is even or 0
        if (numberOfIntersections == 0 || numberOfIntersections % 2 == 0)
        {
            isInside = false;
        }

        return(isInside);
    }