+3 votes

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

Godot version v3.2.3-stable_win64
in Engine by (942 points)

1 Answer

+4 votes
Best answer

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
by (2,260 points)
selected by

I forgot, to know the points of the polygon use the polygon property of Polygon2D:

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

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

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.