0 votes

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 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!

Godot version 3.4.4
in Engine by (20 points)

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

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.