Need help with flying boss AI

Hello, i need a help with my boss AI, i need to make a boss that its head can follow a player by flying/hovering. im pretty new to this, so i don’'t quite understand on how to do advanced scripting
the enemy script i have currently =

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local humanoid = script.Parent
local root = humanoid.Parent.PrimaryPart

local targetDistance = script:GetAttribute("TargetDistance")
local stopDistance = script:GetAttribute("StopDistance")
local damage = script:GetAttribute("Damage")
local attackDistance = script:GetAttribute("AttackDistance")
local attackWait = script:GetAttribute("AttackWait")
local lastAttack = tick()
local animationtrack = humanoid:LoadAnimation(script.Parent.Animation)

function findNearestPlayer()
	local playerList = Players:GetPlayers()
	local nearestPlayer = nil
	local distance = nil
	local direction = nil
	for _, player in pairs(playerList) do
		local character = player.Character
		if character then
			local distanceVector = (player.Character.HumanoidRootPart.Position - root.Position)
			if not nearestPlayer then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
			elseif distanceVector.Magnitude < distance then
				nearestPlayer = player
				distance = distanceVector.Magnitude
				direction = distanceVector.Unit
	return nearestPlayer, distance, direction

	local nearestPlayer, distance, direction = findNearestPlayer()
	if nearestPlayer then
		if distance <= targetDistance and distance >= stopDistance then
		if distance <= attackDistance and tick() - lastAttack >= attackWait then
			lastAttack = tick()
			nearestPlayer.Character.Humanoid.Health -= damage

i also took this from a video on youtube, thanks for anyone that can help

Whats happening here? Whats the error/bug?

i don’t quite understand how to use bodyforces and stuff, since the last time i did was a little bit broken

You should probably learn those, also i really dont see a BodyForce being used in this script.

yeah, the script was only for grounded enemies, thanks for the idea anyways

what do you mean by “grounded” and “air” enemies? Like flying enemies? U can prob just configure the distance, im not too familiar with this code aswell.

Also, i reccomend using pathfinding instead, not too sure if its the best approach but its what i use, heres a video of where i learned it: video from TheDevKing.

You got this, everyone starts with something!

yeah, flying enemies, also thanks dude for the help