• Godot Help
  • Trying to get a bunch of nodes to follow the closest

I am having problems getting nodes to follow the closest relevant node. They behave very weirdly and I think it's probably to do with how I am getting the closest target, explaining's hard so here's some code:

velocity = Vector2().direction_to(closesttarget.position) #* currentspeed
		velocity = velocity * 100

and this is the function that gets closesttarget's value:

func _getclosesttarget():
	var container = get_parent().get_parent()
	var targetsfound = []	
	
	for i in container.get_child_count():
		targetsfound.append(container.get_child(i).get_child(0))
		
	targetsfound.erase(self) #get rid of self
	
	var closesttarget
	var distancetobeat
	var indexdistance
	var selfglobalposition = transform.origin
	var indexglobalposition
	for i in range(0, targetsfound.size()):
		indexglobalposition = targetsfound[i].position
		indexdistance = selfglobalposition.distance_to(indexglobalposition)
		if distancetobeat == null :
			distancetobeat = indexdistance
			closesttarget = targetsfound[i]
		else :
			if indexdistance < distancetobeat :
				distancetobeat = indexdistance
				closesttarget = targetsfound[i]
	return closesttarget
  • Looks like once you've determined the closest target you're setting the direction based on angle from the origin rather than angle from the following node's position. Maybe that first line should be more like:

    velocity = self.global_position.direction_to(closesttarget.global_position)

    Also, the way you have your loops written is certainly functional but you don't really need all those indexes, I think it's more common/idiomatic to iterate using syntax like for child in container.get_children(): and for target in targetsfound:.

Looks like once you've determined the closest target you're setting the direction based on angle from the origin rather than angle from the following node's position. Maybe that first line should be more like:

velocity = self.global_position.direction_to(closesttarget.global_position)

Also, the way you have your loops written is certainly functional but you don't really need all those indexes, I think it's more common/idiomatic to iterate using syntax like for child in container.get_children(): and for target in targetsfound:.

    soundgnome It is working now but the methods you suggested to change the way I iterate the loops don't seem to be working.

      brainsiege Well you would also need to change the inside of the loop correspondingly, i.e. container.get_child(i) would become child and targetsfound[i] would become target. But since your original loops aren't causing any problems it's probably not worth changing in this case, just thought it might be useful to know for the future that you have that option.

      Anyway glad it's working now!