0 votes

Hello there,

I need to add some custom shape UI Buttons to my projects.

First thing that I had in my mind was to use a "Polygon2D", an attached script and handle input events as below:

func _input(event):
    if(event.type == InputEvent.MOUSE_BUTTON):
         if(event.button_index == BUTTON_LEFT):

Everything is fine, except that I need to find when the mouse's cursor is only inside the polygon. Then I thought about triangulate the polygon and find out if the mouse's cursor is "in" a triangle or not (and, of course, parse the triangles within a for/while loop).

So I was wondering if there's another way to do this. Similar to the "mousepick_test" from the 3D demos, but in 2D and maybe using Polygon2D as a shape.

Here's an example of a shape of the button that I need:
enter image description here

in Engine by (104 points)

1 Answer

+1 vote
Best answer

Yes, if that's the approach you want to take, you can use the pickable events with the collision detection of physics bodies to detect mouse events. When input propagates, at the end it will cast a ray into the viewport, and pickables will test for them.

So you would make a physics body of some kind, and instead put a CollisionPolygon2D as the child.

Make sure the physics body's Is Pickable property is flagged to true.

In GDScript you then would add the _input_event() function, and you will get all the mouse events as it "collides" with the polygon collision shape.

extends StaticBody2D

func _input_event(viewport, event, shape_idx):
by (5,200 points)
selected by

Thanks a lot for your answer!

It looks like all I need to do is to set to true the Pickable flag and implement the _input_event function.

You're welcome. ^_^

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 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 webmaster@godotengine.org with your username.