How do i make a object follow the clostest

Godot Version

4.2.2

Question

hai im new here and i wondered how i made a object follow the closest object in a group
by far i only have

extends CharacterBody2D

var speed = 200

func _physics_process(delta):
	var target = get_node("../target").global_position
	look_at(target)
	velocity = transform.x * speed
	move_and_slide()

so here is just following 1 object, how i check to follow the closest on a group?

func _physics_process(delta):
	var target
	var closest_distance = 9223372036854775807 # max int
	for node in get_tree().get_nodes_in_group("<GroupName>"):
		var distance = global_position.distance_to(node.global_position)
		if distance < closest_distance:
			closest_distance = distance
			target = node

	if target:
		look_at(target)
		velocity = transform.x * speed
		move_and_slide()
1 Like