Problem with locating towers

Godot Version

4.2.1

Question

Hello! I’m developing tower defense game, but with goal to keep at least one tower undestroyed instead of protecting the path. I am beginner in godot, so I faced difficulty with how to make enemy locate and walk to closest built tower. Does anyone have any idea how to do that?

You can assign your tower node to a group and find all node in that group.
In the side panel switch from inspector to the Node tab and then Groups. There you can add a group to your tower node.
I have a tower script with class_name Tower,
EDIT: but you can replace the Tower type with Node2D or Node3D to make the function usable for more types.

func get_closest_tower() -> Tower:
	var towers = get_tree().get_nodes_in_group("tower")
	var closest_tower : Tower = null
	var closest_distance : float = 100000 # Use large number to initialize 
	
	for tower in towers:
		var distance = global_position.distance_to(tower.global_position) 
		if distance < closest_distance:
			closest_distance = distance
			closest_tower = tower
	return closest_tower

Then make your enemy move in the direction of the tower or if you are using navmeshagents set the target position to the towers global position.

1 Like

For some reason this function always returns null, at start I got an error: Invalid global_position in base Nil, something like that. When I added checking for null, I found that it always returns null. Do you know how to fix that, maybe I am missing something?

Hey,

is your game 2d or 3d? I changed the code a bit to make it a bit more generic.


func get_closest(group_name : String) -> Node3D:
	var nodes = get_tree().get_nodes_in_group(group_name)
	
	print(nodes.size()) 
	
	var closest_node : Node3D = null
	var closest_distance : float = 100000 # Use large number to initialize 
	
	for node in nodes:
		var distance = global_position.distance_to(node.global_position) 
		if distance < closest_distance:
			closest_distance = distance
			closest_node = node
	return closest_node

I use it this way:

var enemy = get_closest(enemy)
print(enemy)

Did you set up your group name for the tower node?

enemy

If no tower or node with that group has been found it should return null.
I added a print to show how many nodes in wanted group were found for testing.

Thanks a lot! It helped to understand the problem. You see, I am using NavigationObject2d to lead my enemy to the closest tower, but it seems like it’s not building the path, because get_closest() returns the correct node, but enemy does not moving towards it.

What does your enemy code and scene look like?

2D navigation overview — Godot Engine (4.2) documentation in English has some example code and scene setup for using navigation in 2d in case you didn’t see it.

1 Like