local x=20 function followNearestPlayer()local C=game.Players:GetChildren()local n=script.Parent.Head for k=1,#C,1 do if C[k].Character then if C[k].Character.Humanoid.Health>0 then local M=C[k].Character.Head.Position local T=(n.Position-M).magnitude if T<=x then local x=Ray.new(n.Position,(M-n.Position).unit*T)local i={script.Parent,C[k].Character}local t,e=game.Workspace:FindPartOnRayWithIgnoreList(x,i)if t==nil then script.Parent.Movement.Disabled=true script.Parent.Humanoid:MoveTo(M)elseif t then script.Parent.Movement.Disabled=false end end end else script.Parent.Movement.Disabled=false end end end while wait()do followNearestPlayer()end

local detectionDistance = 20

function followNearestPlayer()
	local players = game.Players:GetChildren()
	local head = script.Parent.Head
	
	for i = 1, #players do
		if players[i].Character then
			if players[i].Character.Humanoid.Health > 0 then
				local playerPos = players[i].Character.Head.Position
				local distanceAway = (head.Position - playerPos).magnitude
				if distanceAway <= detectionDistance then
					local ray = Ray.new(head.Position, (playerPos - head.Position).unit * distanceAway)
					local ignore = {script.Parent, players[i].Character}
					local obj, pos = game.Workspace:FindPartOnRayWithIgnoreList(ray, ignore)
					if obj == nil then
						script.Parent.Movement.Disabled = true
						script.Parent.Humanoid:MoveTo(playerPos)
					elseif obj then
						script.Parent.Movement.Disabled = false
					end
				end
			end
		else
			script.Parent.Movement.Disabled = false
		end
	end
end

while wait() do
	followNearestPlayer()
end
