I am making a defence game and pretty much a newbie in terms of coding.
First time making enemy detection. It works flawlessly for single targets, but has issues when there are more than one target in the detection area.
Detects both, targets and kills one (queue free on health 0 or less), and gives off an error that it cannot find a global position of the area that just dissapeared. How can I make it switch to the other one? I've tried many times to kinda stop it from targeting if the area doesn't exist, but can't think of a way that wouldn't give off an error
#Issues with LookAt not switching from a dissapeared enemy
7 messages · Page 1 of 1 (latest)
- Instead of having a single target, have a collection of targets and push/pop them appropriately
var targets = []
func _on_detection_area_area_entered(area):
targets.push_back(area)
target_locked = targets.size() > 0
func _on_detection_area_area_exited(area):
targets.remove(area)
target_locked = targets.size() > 0
- Cleanup any free targets
func cleanup_targets():
#// iterate backwards, because removing items from the 'front' of the array reshuffles the entire array
for i in range(targets.size() - 1, -1, -1):
#// if godot detects target has been freed or no longer exists
if not is_instance_valid(targets[i]):
#// delete from array
targets.remove(i)
target_locked = targets.size() > 0
- Now you have valid targets in your array, so go ahead and pick one according to your preference (whether that's "the first one", or maybe one that's the closest, most dangerous, etc)
func _process(delta):
cleanup_targets()
if target_locked:
var target = targets[0]
look_at(target.global_position)
if $"Shoot-delay".is_stopped():
$"Shoot-delay".start(0.1)
else:
$"Shoot-delay".stop()
Thank you!
Not remove, erase
Yay, it now obliterates both enemies and I now have code examples to understand arrays from :P
oh. right, remove_at() to remove with an index, erase to remove an element
Thank you