Reorient User Camera

I have a mechanic in a game I am working on where, when the user object moves, the camera tilts in the direction the object is moving. My only problem is, sometimes, when both the left and right key are held down one after the other, and then released one after the other, the camera will not reorient itself fully upright. Is there any way for me to do this?

Here is what I have:

local UserInputService = game:GetService("UserInputService")
local camera = game.Workspace.CurrentCamera

UserInputService.InputBegan:Connect(function(InputObject, Processed)
	if InputObject.KeyCode == Enum.KeyCode.A or InputObject.KeyCode == Enum.KeyCode.Left then
			leftdown = true
			if rightdown == false then camera.CFrame = camera.CFrame * CFrame.Angles(0,0,math.rad(-1)) end
	else if InputObject.KeyCode == Enum.KeyCode.D or InputObject.KeyCode == Enum.KeyCode.Right then
			rightdown = true
			if leftdown == false then camera.CFrame = camera.CFrame * CFrame.Angles(0,0,math.rad(1)) end
		end
	end
end)

UserInputService.InputEnded:Connect(function(InputObject, Processed)
	if InputObject.KeyCode == Enum.KeyCode.A or InputObject.KeyCode == Enum.KeyCode.Left then
		if rightdown == false then camera.CFrame = camera.CFrame * CFrame.Angles(0,0,math.rad(1)) end
			leftdown = false
	else if InputObject.KeyCode == Enum.KeyCode.D or InputObject.KeyCode == Enum.KeyCode.Right then
		if leftdown == false then camera.CFrame = camera.CFrame * CFrame.Angles(0,0,math.rad(-1)) end 
			rightdown = false
		end
	end
end)

I think the simplest way to do it is to add an extra variable in your original camera script (if you have one) that accounts for the change in angle, and, checking if the key is held down using your keydown variables, you can see if you have to modify this new variable to construct your final camera CFrame.

UserInputService.InputBegan:Connect(function()
	-- in each key
	keydown = true
end)

UserInputService.InputEnded:Connect(function()
	-- in each key again
	keydown = false
end)

RunService.RenderStepped:Connect(function()

	local cameraCFrame = -- construct normal camera cframe
	
	if holdingObject then
		local objectAngle = CFrame.new()
		if leftdown then
			objectAngle = objectAngle * CFrame.Angles(0, 0, math.rad(-1))
		end
		if rightdown then
			objectAngle = objectAngle * CFrame.Angles(0, 0, math.rad(1))
		end

		cameraCFrame = cameraCFrame * objectAngle
	end

	camera.CFrame = cameraCFrame
end)

If you need help on how to “construct” the camera’s CFrame before adding objectAngle, please reply!

Didn’t really work, it actually had the opposite effect of what I was trying to do.