Bug in Geometry.is_point_in_polygon()?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SteveSmith

I’m running the following code:

var polygon : PoolVector2Array
polygon.append(Vector2(0, 20))
polygon.append(Vector2(100, 20))
polygon.append(Vector2(100, 0))
polygon.append(Vector2(0, 0))

# Returns false:-
var result = Geometry.is_point_in_polygon(Vector2(0,1), polygon)

As far as I can see, “result” should be true since 0, 1 is inside this polygon (which is just a rectangle) but it returns false. Is Geometry.is_point_in_polygon() broken?

:bust_in_silhouette: Reply From: jgodfrey

I was going to suggest that False seems reasonable since your specified point actually lines ON (rather than IN) the polygon’s boundary. But, checking the docs, I see this:

Returns true if point is inside polygon or if it’s located exactly on polygon’s boundary, otherwise returns false.

So, as documented, I would expect your test to return True.

A test of a point at 1, 1 does return True, as expected (as does 0.001, 1). So, at least on the surface, the results of your test do indeed seem wrong.

Interestingly I think it might be the zero causing the issue here. If I use the below I get true as expected as the outcome.

	var polygon : PoolVector2Array
	polygon.append(Vector2(1, 20))
	polygon.append(Vector2(100, 20))
	polygon.append(Vector2(100, 1))
	polygon.append(Vector2(1, 1))
# Returns true:-
	var result = Geometry.is_point_in_polygon(Vector2(100,1), polygon)

Gluon | 2022-12-02 22:19

I’ve discovered that if I invert() the polygon, it does work. Maybe the function only works with anti-clockwise polygon data?

SteveSmith | 2022-12-02 22:54