--Made by Haustier and Luckymaxer

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
