The following C# code snippet can determine whether a point is inside a simple 2-D polygon. Just pass in an array of the polygon vertices and the point. The function returns true if the point is in the polygon and false if it is not.
private bool IsPointInPolygon(PointF[] polygon, PointF point)
{
bool isInside = false;
for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++)
{
if (((polygon[i].Y > point.Y) != (polygon[j].Y > point.Y)) &&
(point.X < (polygon[j].X - polygon[i].X) * (point.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) + polygon[i].X))
{
isInside = !isInside;
}
}
return isInside;
}
Hi, just wanted to let you know that this little snippet saved my ass today, when I was generating procedural 2D polygon-based terrain. :)
ReplyDelete