How to determine what resource is 'near' a mouse click?

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

I have a bunch of images placed on the screen. When the user performs a mouse-click, is there an easy way to tell what image resource is ‘near’ the event.position Vector2? If so, is there a way to modify how far away ‘near’ is?

:bust_in_silhouette: Reply From: Merlin1846

One way to do it is to loop through all the images and calculate the distance between them and the mouse then have all that are near aka within x distance added to a list.

func get_nearby(near: float = 64.0) -> Array:
    var images: Array = $Images.get_children()
    var gmpos: Vector2 = get_global_mouse_position()
    var nearby: Array = Array()
    for i in images:
       if gmpos.distance_to(i.global_position) <= near:
         nearby.push_back(i)
    return nearby

If you want the distance to be exclusive then change <= to <

How would you do that with duplicated image resources?

# setting node name and placing resource on screen
temp_node = get_node(location_info.path + location_info.filename)
var my_copy = temp_node.duplicate()
add_child(my_copy)
my_copy.visible = true
my_copy.set_position(Vector2(xpos, ypos))
my_copy.rect_scale = Vector2(asset_result[0]['scale'],asset_result[0]['scale'])

# tracking arrays
resource_position_array.append([xpos,ypos,my_copy])

The way I was trying to do it was as I duplicated and placed the resource I was saving that value in an array, the cycling through those values on a mouse click event, see below.

func _input(event):
	# Mouse in viewport coordinates.
	if event is InputEventMouseButton:
		# testing for any elements in resource tracker
		if (resource_position_array.size() > 0):
			# looping through position array
			for loop in range(0,resource_position_array.size(),3):
				# setting position values
				var xstart = (resource_position_array[loop][0]-20)
				var xfinish = (resource_position_array[loop][0]+20)
				var ystart = (resource_position_array[loop][1]-20)
				var yfinish = (resource_position_array[loop][1]+20)

				# looking for any resource at that x,y range
				if (event.position.x > xstart and event.position.x < xfinish):
					if (event.position.y > ystart and event.position.y < yfinish):
						alert("Resource Found","Resource Found")

However, this was not working. When I clicked on the middle of the graphic, the event.position was different from the xy in the array. I like your idea better, I’m just not sure how you would cycle through duplicated resources like that.

grymjack | 2022-12-19 01:37