0 votes

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 ?

in Engine by (44 points)

1 Answer

0 votes

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)

        return intersecting_object

    var objects = get_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
by (5,200 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.