-- Gets the closest player within range to the given mob. If the closest player is the player the mob is already following, distance is 2x.
-- Note: If streaming is enabled, MoveTo may produce undesired results if the max distance is ever higher than streaming minimum, such as the enemy
-- appearing to 'idle' if the current distance/magnitude is between the streaming minimum and the max follow distance (including 2x possibility)

function AI:GetClosestPlayer(Mob: MobList.Mob): (Player?, number?)
	local Closest = {Player = nil, Magnitude = math.huge}
	
	local ActivePlayer -- We retain a reference to this, so they have to get further away from the mob to stop following, instead of the usual distance.
	if Mob.Enemy.WalkToPart then
		local Player = Players:GetPlayerFromCharacter(Mob.Enemy.WalkToPart.Parent)
		if Player then
			ActivePlayer = Player
		end
	end
	
	for _, Player in Players:GetPlayers() do
		local Character = Player.Character
		if not Character then continue end
		
		local Magnitude = (Character:GetPivot().Position - Mob.Instance:GetPivot().Position).Magnitude
		local MaxDistance = (ActivePlayer == Player and (Mob.Config.FollowDistance or 32) * 2) or Mob.Config.FollowDistance or 32
		
		if Magnitude <= MaxDistance and Magnitude < Closest.Magnitude then
			Closest.Player = Player
			Closest.Magnitude = Magnitude
		end
	end
	
	return Closest.Player, Closest.Player and Closest.Magnitude
end
