#AI getting the first index of the group array instead of the closest one

1 messages · Page 1 of 1 (latest)

coarse cradle
#

Hello, I'm trying to make a tiger AI that runs after the closest prey within range.
The tiger is running after preys and detecting them, however it is choosing to follow only the first prey within the preyGroup array.
I'd like to know how can I make it follow only the closest prey within range.

Here's the code:

for prey in preyGroup:
if prey !=null:
if global_position.distance_to(prey.global_position) < 280:
STATE = "HUNT"
currentTarget = prey
sprintModif = 4
wandering = false
else:
wanderState()
sprintModif = 1

fierce bolt
#

Set closest_distance to a high number & target_prey to null, loop over all prey, check the distance, if the distance is less than closest_distance set the closest_distance to the current distance + set target_prey to that prey. Once the loop is done, you are left with the closest prey in target_prey.

An alternative is running a lambda function on the preyGroup, which calculate the current distance on each prey, and then you pick the lowest. (This is in the end not too different from above)