local function V(V,s)return math.atan2(s.X*V.Z-s.Z*V.X,s.X*V.X+s.Z*V.Z)end local function s()local s=RootCameraCreator()local j=tick()function s.Update(l)local b=tick()local v=workspace.CurrentCamera local Z=PlayersService.LocalPlayer if j==nil or b-j>1 then s:ResetCameraLook()l.LastCameraTransform=nil end local C=l:GetSubjectPosition()if C and(Z and v)then local s=l:GetCameraZoom()if s<=0 then s=.1 end local Z=l:GetHumanoid()if j and(Z and Z.Torso)then local s=math.min(.1,b-j)local v=l:UpdateGamepad()l.RotateInput=l.RotateInput+v*s local C=Z.Torso.CFrame.lookVector local X=V(C,l:GetCameraLook())if IsFinite(X)then l.RotateInput=Vector2.new(X,l.RotateInput.Y)end end local X=l:RotateCamera(l:GetCameraLook(),l.RotateInput)l.RotateInput=Vector2.new()v.Focus=CFrame.new(C)v.CoordinateFrame=CFrame.new(v.Focus.p-s*X,v.Focus.p)l.LastCameraTransform=v.CoordinateFrame end j=b end return s end return s

local function findAngleBetweenXZVectors(vec2, vec1)
	return math.atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z)
end

local function CreateAttachCamera()
	local module = RootCameraCreator()
	
	local lastUpdate = tick()
	function module:Update()
		local now = tick()
		
		local camera = 	workspace.CurrentCamera
		local player = PlayersService.LocalPlayer
		
		if lastUpdate == nil or now - lastUpdate > 1 then
			module:ResetCameraLook()
			self.LastCameraTransform = nil
		end	
		
		local subjectPosition = self:GetSubjectPosition()		
		if subjectPosition and player and camera then
			local zoom = self:GetCameraZoom()
			if zoom <= 0 then
				zoom = 0.1
			end


			local humanoid = self:GetHumanoid()
			if lastUpdate and humanoid and humanoid.Torso then
				
				-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
				local delta = math.min(0.1, now - lastUpdate)
				local gamepadRotation = self:UpdateGamepad()
				self.RotateInput = self.RotateInput + (gamepadRotation * delta)		
				
				local forwardVector = humanoid.Torso.CFrame.lookVector

				local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
				if IsFinite(y) then
					-- Preserve vertical rotation from user input
					self.RotateInput = Vector2.new(y, self.RotateInput.Y)
				end
			end

			local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
			self.RotateInput = Vector2.new()


			camera.Focus = CFrame.new(subjectPosition)
			camera.CoordinateFrame = CFrame.new(camera.Focus.p - (zoom * newLookVector), camera.Focus.p)
			self.LastCameraTransform = camera.CoordinateFrame
		end
		lastUpdate = now
	end
	
	return module
end

return CreateAttachCamera
