local function u(u,v)return math.atan2(v.X*u.Z-v.Z*u.X,v.X*u.X+v.Z*u.Z)end local function v(u,v)local o=(v:Cross(u)).unit local t=(u:Cross(o)).unit u=u.unit return CFrame.new(0,0,0,o.x,t.x,u.x,o.y,t.y,u.y,o.z,t.z,u.z)end local function o()local v=RootCameraCreator()local o=tick()function v.Update(t)local z=tick()local y=workspace.CurrentCamera local s=PlayersService.LocalPlayer if o==nil or z-o>1 then v:ResetCameraLook()t.LastCameraTransform=nil end local n=t:GetSubjectPosition()if n and(s and y)then local v=t:GetCameraZoom()if v<=0 then v=.1 end if t.LastCameraTransform then local v=t:GetHumanoid()if o and(v and v.Torso)then local o=v.Torso.CFrame.lookVector local z=u(o,t:GetCameraLook())if IsFinite(z)and math.abs(z)>.0001 then t.RotateInput=t.RotateInput+Vector2.new(z,0)end end end local z=t:RotateCamera(t:GetCameraLook(),t.RotateInput)t.RotateInput=Vector2.new()y.Focus=CFrame.new(n)y.CoordinateFrame=CFrame.new(y.Focus.p-v*z,y.Focus.p)t.LastCameraTransform=y.CoordinateFrame end o=z end return v end return o

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 GetOrientationZY(backVector, upVector)
	local rightVector = upVector:Cross(backVector).unit;
	local upVector = backVector:Cross(rightVector).unit;
	backVector = backVector.unit;
	return CFrame.new(0, 0, 0, rightVector.x, upVector.x, backVector.x, rightVector.y, upVector.y, backVector.y, rightVector.z, upVector.z, backVector.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
