Get nearest object to mouse

Godot 4.2.2


I’m making a simple physics simulation, and I need to get the closest object to the mouse cursor to delete it. This function is called and the queue_free() is called on the returned node.I’m calling the function but nothing is happening. Here’s my code:

func get_nearest_object():
	var mouse_pos = get_global_mouse_position()
	var objects = []
		return null # Failure case
	if(objects.size() == 1):
		return objects[0]
	var near_obj = objects[0]
	var near_pos = near_obj.global_position
	var near_sqr = mouse_pos.distance_squared_to(near_pos)
	for i in range(1, objects.size()):
		var obj = objects[i]
		var pos = obj.global_position
		var sqr = mouse_pos.distance_squared_to(pos)
		if(sqr < near_sqr):
			near_sqr = sqr
			near_obj = obj
	return near_obj

I mean everything looks ok…
what does the function return when you run it? null or an object?

Could you also provide the code for how this function is called?

I think get_global_mouse_position gets the canvas item coordinates, not screen space.

Try DisplayServer.mouse_get_position()

I can’t tell what it returns because I’m using the web editor, which doesn’t have debug tools.
It’s called like this:

if Input.is_action_just_pressed("delete"):
	var to_del = get_nearest_object()