How do I make a zombie ai that can chase the player AND non-zombies at the same time?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By thriller1234519

This might be a little too complex of a question, but here goes.
I’m trying to make a top down zombie shooter where the zombies can chase the player.
That much I can figure out on my own. But I want the zombies to ALSO be able to chase after ‘civilians’ in range, based on which ever valid chase target is closest to a given zombie.

How do I make each zombie be able to chase both the player AND other ai?

:bust_in_silhouette: Reply From: exuin

Keep track of all targets by either putting them in a group or using layers, and adding them to an array of targets. Each frame, check which target is closest and chase after that one.

Okay, that makes sense. Noob question, but just to be sure:
How do I check which target is closest? ^^

thriller1234519 | 2023-02-23 21:00

Now that is probably the most asked question and shouldn’t be too hard to find by doing a question search.

Basically you subtract the magnitude of each nodes position vector and luckily Godot has a helper function that does just that distance_to

func get_closest_enemy():
    #zombie_enemies is an Array, the group
	var closest = 1e20
	var closest_enemy = null
	for enemy in zombie_enemies:
        #ignore dead enemies
		if is_instance_valid(enemy) and enemy.health > 0:
			var distance = zombie.global_transform.origin.distance_to(enemy.global_transform.origin)
			if distance < closest:
				closest = cost
				closest_enemy = enemy
	return closest_enemy

Wakatta | 2023-02-23 23:48