3

I want to detect a mouse click (and hold) inside an Area2D, and then detect the mouse release both inside or outside the Area2D.

Here's what I have so far:

extends Area2D #PickArea

func _input_event(viewport, event, shape_idx):
    if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
        if event.is_pressed():
            print("picked")
        else:
            print("released")    ## here be dragons. release only detected inside Area2D

The above works but it only detects the mouse release inside the Area2D. How do I detect the mouse release also outside the Area2D?

Here's the node structure:

enter image description here

mandmeier
  • 355
  • 5
  • 16

1 Answers1

3

You can get input events outside of the Area2D in _input. Use that to get the release:

func _input(event: InputEvent) -> void:
    if (
        event is InputEventMouseButton
        and event.button_index == BUTTON_LEFT
        and not event.is_pressed()
    ):
        print("released")

However, you would only want to get that after you got the press, right? So, let us disable _input on _ready and on _input, and enable it on _input_event:

extends Area2D

func _ready():
    set_process_input(false)

func _input_event(viewport: Object, event: InputEvent, shape_idx: int) -> void:
    if (
        event is InputEventMouseButton
        and event.button_index == BUTTON_LEFT
        and event.is_pressed()
    ):
        print("picked")
        set_process_input(true)

func _input(event: InputEvent) -> void:
    if (
        event is InputEventMouseButton
        and event.button_index == BUTTON_LEFT
        and not event.is_pressed()
    ):
        print("released")
        set_process_input(false)

That should do the trick.

Theraot
  • 31,890
  • 5
  • 57
  • 86