Simple way to move the player to the closest object spawned by the user?

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

The main idea is the user clicks on the screen and spawns an object where they clicked. The player object is meant to move to the closest spawned object and collide with it, which causes it to destroy. Then it moves on to the next closest user spawned object ect. My problem is I can’t figure out a way to check which of the user spawned objects is the closest to the player object.

Please help. I’ve spent all day trying different methods and just can’t seem to get any to work.

1 Like
:bust_in_silhouette: Reply From: jgodfrey

Finding the distance between 2 objects is as simple as using Vector2.distance_to for 2D or Vector3.distance_to for 3D. For sake of discussion, let’s assume 2D.

Assuming $Player has a reference to the player and $Enemy has a reference to an enemy, the distance between them would be:

var dist = $Player.position.distance_to($Enemy.position)

So, using that, you really just need to check the distance between the player and each enemy. As you check the distance to each enemy, you just need to remember the closest one.

To do that, you need to have access to all enemies. One way to do that is to place the enemies in a common group. Then, you can easily get access to all enemies to check their distances.

That could look something like this (typed in message and untested, but should be close):

func get_closest_enemy():
    var min_dist = 99999
    var min_enemy
    var enemies = get_tree().get_nodes_in_group("enemies")
    for enemy in enemies:
        var dist = $Player.position.distance_to(enemy.position)
        if (dist < min_dist):
            min_dist = dist
            min_enemy = enemy
    return min_enemy

Note, this assumes that your enemies are all in a group named “enemies”. This should check the distance between each enemy and the player, and will return a reference to the closest enemy.

That should get you close. Just season to taste…

Thank you so much for your reply. I’ve been trying to figure this out for hours now. I just want to confirm that you would put the script above on the main scene script right?

MyGrandfather | 2020-04-17 03:52

It sort of depends on your scene structure, but yeah, I’d expect it to go on the main scene. The way it’s written, the Player object is a first-level child of the scene where the script lives, though, that could be easily changed as needed…

I realize now too that I had “enemy” in my head when writing it, even though you never referenced enemies in your original post. My enemy references are your “spawned objects”.

jgodfrey | 2020-04-17 13:04