Is there a code snippet to do the following?

I have a 2d scene, with 3 objects (these are items, I am using fruits for example -> apple, banana and an orange).
I would like to drag the items around the screen.
If I drag an item, it should become the topmost item.
when i drop the item over another item, I want it to be on top of it.
since the example is 3 items, I would like to stack 3 items.
of course if I have more items I would like to stack more.
I have difficulty how to write this. I am new to gdscript.
Is there a quick code snippet or example out there that does exactly this without requiring too much modification.
for me this is very important in the style of game I would like to try.

There are a lot of ways you could do it. The first idea that comes to my mind:

  • Each fruit has a variable to the fruit that it is sitting on top of. That variable can be empty. If that variable has another fruit, then in _process you check that other fruit's position and move the "above" fruit to be above it.
  • When you drop a fruit, you check to see if you've dropped it on another fruit. If you have, then you set it to that variable.
  • When you pick up a fruit, you check to see if that variable has a fruit below it. If it does, then you disconnect the variable so that it no longer moves with that fruit.
  • You need to be careful when you drop a fruit to make sure that you find the "top" fruit to set to the variable. You wouldn't want two fruits on the same bottom fruit.

What you will have made then is essentially a singly-linked list of fruit stacked on top of each other.