-- Necessery Functions


local ErrorPart = nil
local function GetValidPartToLookAt(Char, bodypart)
	local pHum = Char:FindFirstChild("Humanoid")
	if not Char and pHum then return nil end
	local pIsR6 = (pHum.RigType.Value==0)
	if table.find({"Torso", "UpperTorso"}, bodypart) then
		if pIsR6 then bodypart = "Torso" else bodypart = "UpperTorso" end
	end
	local ValidPart = Char:FindFirstChild(bodypart) or Char:FindFirstChild("HumanoidRootPart")
	if ValidPart then return ValidPart else
		if ErrorPart ~= bodypart then
			--warn(Body.Name.." can't find part to look: "..tostring(bodypart))
			ErrorPart = bodypart
		end
		return nil end
end

local function getClosestPlayer() -- Get the closest player in the range.
	local closest_player, closest_distance = nil, LookAtPlayerRange
	for i = 1, #SearchLoc do
		for _, player in pairs(SearchLoc[i]:GetChildren()) do
			if player:FindFirstChild("Humanoid") and player ~= Body 
				and (Players:GetPlayerFromCharacter(player) or LookAtNonPlayer) 
				and GetValidPartToLookAt(player, PartToLookAt) then
				
				local distance = (Core.Position - player.PrimaryPart.Position).Magnitude
				if distance < closest_distance then
					closest_player = player
					closest_distance = distance
				end
			end
		end
	end
	return closest_player
end

local function rWait(n)
	n = n or 0.05
	local startTime = os.clock()

	while os.clock() - startTime < n do
		game:GetService("RunService").Heartbeat:Wait()
	end
end

local function LookAt(NeckC0, WaistC0)
	if not IsR6 then
		if Neck then Neck.C0 = Neck.C0:lerp(NeckC0, UpdateSpeed/2) end
		if Waist then Waist.C0 = Waist.C0:lerp(WaistC0, UpdateSpeed/2) end
	else
		if Neck then Neck.C0 = Neck.C0:lerp(NeckC0, UpdateSpeed/2) end
	end
end
