How to check if a point is in a Polygon2D

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

Can anyone please tell that how will I check if a point is in a Polygon2D or not

in my case the Polygon is a rhombus with one diagonal 128 and other 64. The longer diagonal is horizontal and smaller diagonal is vertical

:bust_in_silhouette: Reply From: estebanmolca

Hi…A technique is explained in the godot manual:

Godot has a class called Geometry and one of its methods is just what you are looking for:

In godot it would be used like this, passing it an array with the points of the polygon:

var polygon = [Vector2(0,0), Vector2(1,0), Vector2(1,1), Vector2(0,1)]
print(Geometry.is_point_in_polygon(Vector2(0.5,0.5),polygon)) #print true
print(Geometry.is_point_in_polygon(Vector2(2.5,0.5),polygon)) #print false

I forgot, to know the points of the polygon use the polygon property of Polygon2D:
Polygon2D — Godot Engine (stable) documentation in English

estebanmolca | 2021-08-18 07:31

But I have doubt in second parameter of this method is_point_in_polygon
Can it be $Polygon2D.get_polygon()?

Help me please | 2021-08-18 09:47

Yes… If you can’t make it work, tell me and I’ll prepare an example

estebanmolca | 2021-08-18 10:35

Thanks a lot!
You did a great help to me. I was earlier going to do very stupid things to make this work.
But now

func _input(event):
	if event.is_action_pressed("click"):
		if Geometry.is_point_in_polygon(event.position, $Polygon2D.get_polygon()):
			print("successs") ### And it prints success

Help me please | 2021-08-18 11:32

Very good. I’m glad I was helpful. The Geometry class has other useful functions like doing Boolean operations between polygons, intersections etc.

estebanmolca | 2021-08-18 11:48

1 Like