Overlapping collision layers with mouse input - selecting the correct layer

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lordtopcat

In my project, I have nodes generated in code with collision layers to detect mouse input. When you click on each “object”, a menu pops up with various actions depending on the type of object.

By itself, this works perfectly, for example:

enter image description here

However, when one of the layers overlaps and I click on the object on top, it thinks I’m clicking on the layer below:
enter image description here

The script attached to all of my “object” scenes (the only difference in my player scene is I emit the signal with “avatar” instead of “object”):

signal clicked(node, type)

func _input_event(viewport, event, _shape_idx):
    if event.is_action_pressed("lmb"):
	    emit_signal("clicked", self, "object")

As I am generating all my objects in the main scene (they load from a JSON file), I connect the clicked signal to the function to select the right menu

for x in no_objects:
    var obj = load(data.objects[x].scene_path).instance()
    obj.position += Vector2(data.objects[x].position_x, data.objects[x].position_y)
    obj.connect("clicked", self, "_on_object_scenery_clicked")
    obj.object_name = data.objects[x].object_name

So, finally my question: How can I get Godot to interpret the correct menu to choose depending on “what’s on top”? I’ve tried playing with the z-index of all my objects, re-arranging my scene tree all to no avail.

Help - please! :slight_smile:

:bust_in_silhouette: Reply From: jtarallo

So, if I understand correctly, you have an _input_event function in each object that can be touched?

I think the best approach for the end result you need would be to handle input events in your scene, test collisions with all touchable objects (for this you could create a proxy to detect collisions with it setting its position on mouse’s position, store collisions in an array for that touch event) and use the z-index of the objects collided with to know which one to “click”.

Hope it helps