• 2D
  • Area2D click detection

Hello everyone, I have been struggling with a certain behaviour of Godot when using Area2D to detect clicks.

I have a background and a few actors on the top of it in my scene. What happens is the following: every time I play the project, whenever I click on an actor, I got a different behaviour on who handles the click (input event). Sometimes the actor consumes the input event (which is the behaviour I would expect), but sometimes the background does it. I do not change anything in the code two have these different behaviour. I have tried to place the actors as the first ones on the scene tree, but that does not seem to help. I have no idea on what is causing this randomness.

Has anyone experienced something similar? Any ideas of what can be happening?

Thanks, Matheus

8 days later

How are you handling the click detection?

6 days later

Hi Nathan, thanks for the reaction. Both background and actor are Area2D with a CollisionShape2D under it. Then I use the __input_event_ function in a similar way (see below).

Just to give you a flavour of what happens, I executed the project 10 times. When I clicked the actor, 7 times the background captured the event and 3 times the actor..

Background:

func _input_event(viewport, event, shape_idx):

if event.is_action_pressed('click'):
	if not get_tree().is_input_handled():
		print('Background handled the event.')
		get_tree().set_input_as_handled()

Actor:

func _input_event(viewport, event, shape_idx):
	if event.is_action_pressed('click'):
		if not get_tree().is_input_handled():
			print('Actor handled the event')
			get_tree().set_input_as_handled()

Do you need the background to register the event? If not, you could just remove the code.

@nathanjwtx I'm assuming the BG handles the camera/view panning.


@mardenarts All I get in godot 3.1.1 is "Actor handled the event" every single time. Even when I click what is most definitely out of "Actor" bounds.

@nathanjwtx I see your point. I do need the event though. @Megalomaniak Thanks for testing it out. That is my desired behaviour. I suspect it has to do with the structure of my scene then. I will try to rebuild it from scratch and see where it takes me.

Actually, I just copy and pasted your code, then changed the _input_event() to _input() and didn't bother to think that I should set up ray-casting too, so pretty sure it wasn't working right anyways.

Anyways, I'd create 2 groups(at the least) one for the background and one for the actors, assign each respective area and it's children to appropriate group and then try to pick them with a check for the group. Might help.