Sounds like it might not be comparing the distances correctly then, or the code doesn't properly iterate through all possible units. Looking at the code, I think it might be lines 17
and 35
, which always set the closest distance to the last element in the array. I think what you may want to do is pull the closest target outside of the loop and then apply it at the end. Something like this:
func _target():
var ppp = get_parent().get_parent().get_parent()
if p.stance == "Aggressive":
var bodies = get_overlapping_bodies()
var closest_body = null;
var closest_distance = 0;
for body in bodies:
if body.is_in_group("Unit"):
if body.tribe == "Romans":
if ppp.Romans == "Hostile":
body.sighted = 1
if not p.exhausted == true \
and not body.action == "Housed":
print("target!")
# if closest_body is null, then set it to this body and move on
if (closest_body == null):
closest_body = body
closest_distance = closest_body.global_transform.origin.distance_to(global_transform.origin)
# otherwise, compare distances
else:
var new_dist = body.global_transform.origin.distance_to(global_transform.origin)
if (new_dist < closest_distance):
closest_body = body
closest_distance = new_dist
if body.tribe == "Votadini":
if ppp.Votadini == "Hostile":
body.sighted = 1
if not p.exhausted == true \
and not body.action == "Housed":
# if closest_body is null, then set it to this body and move on
if (closest_body == null):
closest_body = body
closest_distance = closest_body.global_transform.origin.distance_to(global_transform.origin)
# otherwise, compare distances
else:
var new_dist = body.global_transform.origin.distance_to(global_transform.origin)
if (new_dist < closest_distance):
closest_body = body
closest_distance = new_dist
# after the loop, check the closest body and set the variables based on it
if (closest_body != null):
closest_body.sighted = 1
p.target = closest_body
p.action = "Walking_To_Attack"
Edit: I also uploaded the example code above as text file, since the code block doesn't show the longer code statements very well.