local function f(f,I)return math_atan2(I.X*f.Z-I.Z*f.X,I.X*f.X+I.Z*f.Z)end local function I()local I=RootCameraCreator()local Y=tick()function I.Update(Z)local y=tick()local V=workspace.CurrentCamera if Y==nil or y-Y>1 then I:ResetCameraLook()Z.LastCameraTransform=nil end local m=Z:GetSubjectPosition()if m and V then local I=Z:GetCameraZoom()if I<=0 then I=.1 end local k=Z:GetHumanoid()if Y and(k and k.Torso)then local I=math_min(.1,y-Y)local V=Z:UpdateGamepad()Z.RotateInput=Z.RotateInput+V*I local m=k.Torso.CFrame.lookVector local C=f(m,Z:GetCameraLook())if IsFinite(C)then Z.RotateInput=Vector2_new(C,Z.RotateInput.Y)end end local C=Z:RotateCamera(Z:GetCameraLook(),Z.RotateInput)Z.RotateInput=ZERO_VECTOR2 V.Focus=CFrame_new(m)local n=CFrame_new(m-I*C,m)V.CFrame=n Z.LastCameraTransform=n end Y=y end return I end return I

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
		
		if lastUpdate == nil or now - lastUpdate > 1 then
			module:ResetCameraLook()
			self.LastCameraTransform = nil
		end	
		
		local subjectPosition = self:GetSubjectPosition()		
		if subjectPosition 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 = ZERO_VECTOR2

			camera.Focus = CFrame_new(subjectPosition)
			local newCFrame = CFrame_new(subjectPosition - (zoom * newLookVector), subjectPosition)
			camera.CFrame = newCFrame
			self.LastCameraTransform = newCFrame
		end
		lastUpdate = now
	end
	
	return module
end

return CreateAttachCamera
