Working with nodes in a custom resource.

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

I’ve been working on making the projectile behavior in my game modular using custom resources so it can be reused more easily. Basic movement (like firing straight, or at an angle or whatever) haven’t been too tough, but I’m stumped on how to make my target seeking behavior work inside a resource. This is the relevant function (thanks to an awesome user from here!) that’s giving me difficulty.

func get_closest_enemy():
	var enemies = get_tree().get_nodes_in_group("enemy")
	var closest_enemy = null
	var min_distance = INF

	for enemy in enemies:
		var distance = self.global_position.distance_squared_to(enemy.global_position)
		if distance < min_distance:
			min_distance = distance
			closest_enemy = enemy
	return closest_enemy

It works beautifully in the script attached to a homing missile, but I’m unsure of the best way to pass the enemy nodes to it as a resource since get_tree() cannot be used. In the missile script, it’s called in _physics_process so it updates continuously based on the missile’s position and can seek out a new target if its current one dies. I’m not quite sure how best to approach that from a resource either. Any pointers would be greatly appreciated!

have you want new target ?

Add enemies entering the scene to a Array. Remove dead enemies from the “Array”.

example:
enemys_array[enemy1,enemy2,enemy3,enemy4,…etc]

target = enemys_array[0] // enemy1
enemy die enemy1
enemys_array.remove[0]

target = enemys_array[0] // enemy2

similar to this
I hope I explained

ramazan | 2022-08-04 11:33