local function G(G,t)return math.atan2(t.X*G.Z-t.Z*G.X,t.X*G.X+t.Z*G.Z)end local function t()local t=RootCameraCreator()local q=tick()function t.Update(U)local O=tick()local j=workspace.CurrentCamera local c=PlayersService.LocalPlayer if q==nil or O-q>1 then t:ResetCameraLook()U.LastCameraTransform=nil end local L=U:GetSubjectPosition()if L and(c and j)then local t=U:GetCameraZoom()if t<=0 then t=.1 end if U.LastCameraTransform then local t=U:GetHumanoid()if q and(t and t.Torso)then local q=t.Torso.CFrame.lookVector local O=G(q,U:GetCameraLook())if IsFinite(O)and math.abs(O)>.0001 then U.RotateInput=U.RotateInput+Vector2.new(O,0)end end end local O=U:RotateCamera(U:GetCameraLook(),U.RotateInput)U.RotateInput=Vector2.new()j.Focus=CFrame.new(L)j.CoordinateFrame=CFrame.new(j.Focus.p-t*O,j.Focus.p)U.LastCameraTransform=j.CoordinateFrame end q=O end return t end return t
-- May return NaN or inf or -inf
-- This is a way of finding the angle between the two vectors:
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

			if self.LastCameraTransform then
				local humanoid = self:GetHumanoid()
				if lastUpdate and humanoid and humanoid.Torso then
					local forwardVector = humanoid.Torso.CFrame.lookVector

					local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
					if IsFinite(y) and math.abs(y) > 0.0001 then
						self.RotateInput = self.RotateInput + Vector2.new(y, 0)
					end
				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
