This is the easiest and most efficient way that I've found so far:
onready var GrabArea = $Area
#var ClosestObject = null # Optional
func _unhandled_input(_event):
if Input.is_action_just_pressed("ui_accept"):
var AvailableObjects = GrabArea.get_overlapping_bodies()
if !AvailableObjects: return
var Array_ = []
var ArrayPosition: int = -1
Array_.resize(AvailableObjects.size())
for element in AvailableObjects:
var Distance = element.global_transform.origin.distance_to(global_transform.origin)
ArrayPosition += 1
Array_[ArrayPosition] = Distance
for element in AvailableObjects:
var Distance = element.global_transform.origin.distance_to(global_transform.origin)
if Distance == Array_.min():
element.queue_free()
#element = ClosestObject # Optional
Create an Area node in your player scene.
Make sure ONE layer is dedicated to collecting items, otherwise, the Area node will calculate objects not relating to collectable items--it will mess up the code.
Add all collectable items in the layer dedicated to collecting items.
For the Area node, uncheck "Monitorable", uncheck all of its collision layer bits, and select ONLY the layer dedicated to collecting items for its collision mask.