godotgdscript

How can I extend Godot's Button to distinguish left-click vs right-click events?


I created a button using the built-in Button class, and set the button mask to BUTTON_MASK_LEFT | BUTTON_MASK_RIGHT. Now both left- and right-click cause the 'pressed' signal to be emitted, but I need a way to tell whether the user clicked with the left or right mouse button.


Solution

  • Extend the Button class, and create and emit custom signals when the button gets left-clicked or right-clicked.

    In Godot 4:

    class_name EventButton
    extends Button
    
    signal left_click
    signal right_click
    
    func _ready():
        gui_input.connect(_on_Button_gui_input)
    
    func _on_Button_gui_input(event):
        if event is InputEventMouseButton and event.pressed:
            match event.button_index:
                MOUSE_BUTTON_LEFT:
                    left_click.emit()
                MOUSE_BUTTON_RIGHT:
                    right_click.emit()
    

    In Godot 3:

    class_name EventButton
    extends Button
    
    signal left_click
    signal right_click
    
    func _ready():
    # warning-ignore:return_value_discarded
        connect("gui_input", self, "_on_Button_gui_input")
    
    func _on_Button_gui_input(event):
        if event is InputEventMouseButton and event.pressed:
            match event.button_index:
                BUTTON_LEFT:
                    emit_signal("left_click")
                BUTTON_RIGHT:
                    emit_signal("right_click")