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.
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
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 gettree() cannot be used. In the missile script, it's called in _physicsprocess 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!