How to make a custom shape UI Button?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By radubolovan
:warning: Old Version Published before Godot 3 was released.

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):
            if(event.pressed):
                print("pressed")
            else:
               print("released")

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:

:bust_in_silhouette: Reply From: avencherus

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):
	print(event)

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.

radubolovan | 2016-11-28 11:41

You’re welcome. :slight_smile:

avencherus | 2016-11-28 13:34

Hi! I made this and it works :D, but when I hold down the mouse and move it outside the polygon, there is no released detection ):, what could I do?

JoluMorsanDev | 2022-03-12 21:24