Drag&drop only the topmost item when collision shapes overlap

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

I’m very new to Godot and programming things that are not CYOA games.
I have a dress-up mechanic in my game. I was able to set drag&drop script (copied from this forum, I believe), looking like this:

extends StaticBody2D

var can_drag = false
var grabbed_offset = Vector2()

func _input_event(_viewport, event, _shape_idx):
	if event is InputEventMouseButton:
		can_drag = event.pressed
		grabbed_offset = position - get_global_mouse_position()

func _process(_delta):
	if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT) and can_drag:
		position = get_global_mouse_position() + grabbed_offset

It works until there are two collision shapes overlapping. Then clicking in the overlapping area affects all the overlapping nodes, and I would like it to affect only the one on the top. How do I approach this?

:bust_in_silhouette: Reply From: CollCaz

Instead of having the drag and drop code be part of your item or whatever, have it in a seperate Control node that you instance as a child of your uhh dress?

make sure the instanced Control node is the same size as your item and it’s Mouse filter property is set to stop, this will stop mouse events from propagating to other nodes.

This will also make your drag and drop code reusable!

here is my code for reference:

extends Control


@onready var parent := get_parent()


func _gui_input(event):
	if event is InputEventScreenDrag:
		parent.position += event.relative

I have this script attached to a control node called Drag&Drop that i simply instance as a child of any node i would like to be able to drag around