Help finding nearest object(and working out the proper code I just realized I need this done in the next six days)

Well you should put it in a function, something like:

# Pretend that this is an array full of CharacterBody2D node references
var livestock = []
var bat = $bat   # Again, pretend this is a reference to your bat object

func _process():
    var closest_animal = find_closest_animal()

    # Insert your own movement code here
    # For example:
    # velocity = (closest_animal.global_position - bat.global_position).normalized()
    # move_and_slide()

func find_closest_animal():
    var lowest_distance = INF    # Initialized as infinity to avoid unintended behaviour at large distances
    var closest_animal
    for animal in livestock:
        var distance = animal.global_position.distance_squared_to(bat.global_position)
    
        # Check whether the distance to the animal is lower
        # than the previously checked animals
        if distance < lowestDistance:
            closest_animal = animal       # Set this animal as the closest animal
            lowest_distance = distance    # Update the lowest distance found
    
    # This is an if-statement that evaluates whether an animal was found
    # It will usually only run if there are no valid animal instances
    if !is_instance_valid(closest_animal) or lowest_distance == INF:
        WARN_PRINT("No valid animal found to follow!");
        return

    return closest_animal
    

1 Like