Topic was automatically imported from the old Question2Answer platform.
Asked By
shreyk27
I am currently working on a 2d card trading game, with card having a functionality to be selected on a click, the cards will be overlapping each other as instanced. I tried using intersect_point() method it worked, but in the game there would be a situation arriving in which the cards would far away from other card object and the intersect_point() which is not as desired so, there is an idea of implementing a method which will register the mouse click event and will search for the closest card to the event location among the other cards.
So , is there any method for the above query by default or should i go about creating a specific one. If yes, than how ?
Probably the simplest thing is to register the relevant objects (nodes) into an Array. Then when an intersection test fails, check them all and see which one has the least distance to the cursor position.
Something like:
func clicked(mouse_pos : Vector2) -> Node:
var intersecting_object = get_intersection(mouse_pos)
if(intersecting_object):
return intersecting_object
var objects = get_objects()
if(objects.empty()):
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