godot find nearest node code example

Example: godot find nearest node

func respawn_player():
    # get spawn nodes
    var spawn_points = get_tree().get_nodes_in_group("space_stations")

    # assume the first spawn node is closest
    var nearest_spawn_point = spawn_points[0]

    # look through spawn nodes to see if any are closer
    for spawn_point in spawn_points:
         if spawn_point.global_position.distance_to(player.global_position) < nearest_spawn_point.global_position.distance_to(player.global_position):
            nearest_spawn_point = spawn_point

    # reposition player
    player.global_position = nearest_spawn_point.global_position

Tags:

Misc Example