Im trying to make tower defense game when a collision hitbox range having some enemies entered it has to clear all inside its hitbox. But it only get newest enemy come to collision shape
extends Area2D
const dot = preload("res://NodeFolder/dot.tscn")
var enemy = null
func _physics_process(delta):
if enemy != null:
look_at(enemy.global_position)
func _on_area_entered(area):
if area.get_parent() is PathFollow2D:
enemy = area
StartAttacking()
func StartAttacking():
while true:
if enemy != null:
var NewDot = dot.instantiate()
visual.add_child(NewDot)
NewDot.global_position = muzzle_2d.global_position
NewDot.Target = enemy
NewDot.rotation = rotation
await get_tree().create_timer(0.5).timeout
You should keep track of all enemies instead of only one.
var enemies_within_range = []
When an enemy enters/exits, add/remove it to the enemies_in_range array.
func _on_area_entered(area):
if area.get_parent() is PathFollow2D:
enemies_within_range.append(area) # Add entered enemy to the list
func _on_area_exited(area):
if area.get_parent() is PathFollow2D:
enemies_within_range.erase(area)
Then, you could also handle the attacking with a timer instead of creating a timer every time.
func _on_attack_timer_timeout():
attacking = true
And use that like this:
func _process(delta):
if attacking && enemies_within_range.size() > 0:
var target = enemies_within_range[0]
if target != null:
var NewDot = dot.instantiate()
visual.add_child(NewDot)
NewDot.global_position = muzzle_2d.global_position
NewDot.Target = target
NewDot.rotation = rotation
attacking = false
else:
enemies_within_range.erase(target)
Thanks!, After reviewed your code i understand how it is work so i created my own based on what you did
extends Area2D
@onready var visual = $"../Visual"
@onready var muzzle_2d = $Muzzle2D
@onready var animation_magic = $AnimationMagic
const dot = preload("res://NodeFolder/dot.tscn")
var enemies = []
var Target = null
var target_found = false
func _physics_process(delta):
for enemy in enemies:
if enemy != null:
look_at(enemy.global_position)
func _on_area_entered(area):
if area.get_parent() is PathFollow2D:
var new_enemy = area
enemies.append(new_enemy)
StartAttacking()
func _on_area_exited(area):
if area in enemies:
enemies.erase(area)
if area == Target:
Target = null
target_found = false
func StartAttacking():
while true:
for enemy in enemies:
if enemy != null:
if enemy.get_parent().Health <= 0 :
print("Dont change")
else:
target_found = true
Target = enemy
break
if not target_found:
print("NOTHING")
await get_tree().create_timer(1).timeout
func _ready():
while true:
if target_found == true:
var newDot = dot.instantiate()
visual.add_child(newDot)
newDot.global_position = muzzle_2d.global_position
newDot.Target = Target
newDot.rotation = rotation
await get_tree().create_timer(1).timeout