All pastes #2110908 Raw Edit

Mine

public text v1 · immutable
#2110908 ·published 2012-02-07 18:57 UTC
rendered paste body
public static bool PointLineListContains(Vector2 a, Vector2[] b)
{
    // Pick a point far away from a.
    Vector2 c = a + (RandomHelper.RandomVector2() * int.MaxValue);

    // Count the number of times ab intersects with the polygon.
    int intersectCount = 0;
    Vector2 collisionPos;
    for (int i = 0; i < b.Length; i++)
    {                
        if (LineLineIntersects(a, c, b[i], b[(i + 1) % b.Length], out collisionPos))
        {
            intersectCount++;
        }
    }

    // Odd intersections means the point is in the polygon
    return (intersectCount % 2 != 0);
}

public static bool LineLineIntersects(Vector2 a, Vector2 b, Vector2 c, Vector2 d,
    out Vector2 point)
{
    point = Vector2.Zero;

    float r, s;
    float denominator = (b.X - a.X) * (d.Y - c.Y) - (b.Y - a.Y) * (d.X - c.X);

    // If the denominator in above is zero, AB & CD are colinear
    if (denominator == 0)
    {
        return false;
    }

    float numeratorR = (a.Y - c.Y) * (d.X - c.X) - (a.X - c.X) * (d.Y - c.Y);
    r = numeratorR / denominator;

    float numeratorS = (a.Y - c.Y) * (b.X - a.X) - (a.X - c.X) * (b.Y - a.Y);
    s = numeratorS / denominator;

    // non-intersecting
    if (r < 0 || r > 1 || s < 0 || s > 1)
    {
        return false;
    }

    // find intersection point
    point.X = a.X + (r * (b.X - a.X));
    point.Y = a.Y + (r * (b.Y - a.Y));

    return true;
}