How do I get my code to recognize clones?

v4.2.1

I have a script that has a blue square (human) seek out a green circle (food) within range and move towards it. I also have another script that duplicates the green circles 30-50 times in random places in the scene. The issue is that the “food-seeking” code only recognizes the original green circle, so the blue square just ignores the clones and only seeks out the original green circle. How do I have the code also recognize clones?


You are using get_child(1) to find the food (line 93)

Without changing much of your code you’d rather use find_children()

So something like

find_children("*food*", "Node2D", false, false)

The * are for completion of the name - so “*food” will accept “TESTfood” for example

Then you’ll have a list of all the food nodes, and you can seek the closest one


PS: when posting code try copying it into a code quote
```gdscript
code goes here
```
instead of a screenshot, so it’s selectable text

2 Likes

I implemented the find_children() method into my code as such:

func scanClosestFood():
	FoodSources = get_parent().find_children("*Food*", "", true, false)
	closest_food = FoodSources[0]
	for n in range(FoodSources.size()):
		var food_position = FoodSources[n].position
		if position.distance_to(food_position) < position.distance_to(closest_food.position):
			closest_food = FoodSources[n]
			print(closest_food)
	return closest_food
func movementDictation():
	if isSafe == false:
		escapeEnemy()
		print("AH!")
	else:
		scanClosestFood()
		if FoodSources.size() != 0:
			if position.distance_to(scanClosestFood().position) <= investigation_range:
				foodSpotted()
				print("Yum!")
			else:
				wander()
		else:
			wander()
func moveTowards():
	if position.distance_to(scanClosestFood().position) <= speed:
		velocity = position.direction_to(scanClosestFood().position) * speed
	else:
		velocity = position.direction_to(scanClosestFood().position) * speed
	move_and_slide()

But the code keeps ignoring the clones and only recognizes the original green circle. I printed the array “FoodSources” many times during runtime, and the array includes all of the clones (as it should). But the “scanClosestFood” function never returns anything other than the original green circle.

It looks like you are using naming conventions for a language other than GDScript, but it looks like you’re using GDScript. So try this:

func scan_closest_food():
	var food_sources = get_owner().find_children("*Food*", "", true, false)
	var closest_food = food_sources.front()
	for food in food_sources:
		if position.distance_to(food.position) < position.distance_to(closest_food.position):
			closest_food = food
			print(closest_food)
	return closest_food