Point at more than one target

Godot Version

Replace this line with your Godot version

Question

I want a gun/area2d to point at an enemy, how do I code this. If I target one enemy node than the gun only points at that enemy and once they die the game crashes because it's still trying to look at that enemy even though it's not in the game anymore, do need some sort of class thing for the enemies so the gun can point at any enemy. If there is no enemy in range, how do I make so the gun knows that.

can you show your code?

I don’t think it will help
but sure.
never mind I have gotten rid of anything I had trying different things to fix it, so my code doesn’t even relate my problem anymore

heres a way to deal with multiple enemies:

var current_target
var targets

func _physics_process(delta):
    if current_target:
        look_at(current_target.global_position)

func _on_area_entered(area):
    targets.append(area)
    if current_target == null:
        current_target = area

func _on_area_exited(area):
    targets.erase(area)
    if current_target == area:
        if not targets.is_empty():
            current_target = targets[0]

You need to connect the area_entered and area_exited signal to the methods

but how do I know who the enemy is

The easiest way would be to set all enemies on the same collisionlayer and then have the area only check for this collisionlayer on the mask

1 Like

But I only know how to make it target whatever I drag into its code with ctrl

well there are several ways you can make it target other objects.
One way is to use an area2d to detect all targets nearby, a second way is to put all targets in a “group” and then reference that group in your script

ok, but like hooow do I these things

Well for the area i posted code already above.
The groups would be for the enemy either in the editor or in code:

func _ready():
    add_to_group("enemy")

and to reference this group you can do:

get_tree().get_nodes_in_group("enemy")

In the code from before when you used var target and var target_enemy, what are these, did you use add_to_group(“”) or what.

no they are the enemies that enter the area2d. You have to connect the body_entered and body_exited signal from the area2d to these methods

so anything that enters the zone is counted as an enemy?

and will be treated as target in the code and if so why are there two target var

anything that is on the collision-layer which corresponds to the collisionmask of the area2d

There are 2 target vars to have one current_target and an array of all other possible targets in the area in case the current_target disappears