how to attack next target in area2D?

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

my tower just atck the first enemy enter area2d, and ignore all enemy that already inside aread 2d.

1how should i make my tower attack the rest enemy in area?
2 how can i make my tower attck enemy that close to end goal, or atck enemy that have low health first?

func target_attk(delta):
	if target:
		var target_dir = (target.global_position - global_position).normalized()
		var my_current_dir = Vector2.RIGHT.rotated($turrent.global_rotation)
		$turrent.global_rotation = my_current_dir.linear_interpolate(target_dir,turrent_rotate_speed * delta).angle()
		if target_dir.dot(my_current_dir) > 0.9 :
			shoot()

func _on_range_Area2D_body_entered(body: Node) -> void:
	if body.is_in_group("enemy"):
		target = body


func _on_range_Area2D_body_exited(body: Node) -> void:
	if body == target:
		target = null

Perhaps make target be an array instead of a variable.
Then, the tower will attack the first enemy.
When the enemy’s health reaches 0, or the enemy leaves the Area2D…
-If the enemy died, have it emit a signal before dying. The tower should listen for this signal. When the signal is received, pop the first value of the target array.
-If the enemy left the range of the tower, simply pop the first value of said array.

System_Error | 2020-03-23 12:44

:bust_in_silhouette: Reply From: njamster

how should i make my tower attack the rest enemy in area?

Right now, you’re save the enemy to be attacked in a variable called target. That will work fine for the first enemy entering the Area2D, but once a second enemy enters the Area2D, it will become the new target and your cannon forgets about the first enemy. To avoid that, you’d need to keep a list of enemies inside the Area2D:

var target_list = []

func _on_range_Area2D_body_entered(body: Node) -> void:
    if body.is_in_group("enemy"):
        target_list.append(body)    

func _on_range_Area2D_body_exited(body: Node) -> void:
    if body.is_in_group("enemy"):
        target_list.erase(body)

how can i make my tower attck enemy that close to end goal, or atck enemy that have low health first?

Now that you have a list of all enemies in reach (i.e. inside your towers Area2D), you can simply loop over it and select the best target (here: the target with the lowest health, assuming all your enemies have a property called health):

func target_attk(delta):
    var best_target = null

    for target in target_list:
        if best_target == null:
            best_target = target
        elif target.health < best_target.health:
            best_target = target

    # your code here