How can I make the camera rotate upon right click properly in my build mode?

I am working on a build mode for my game. The camera moves perfectly fine, however, I want to allow the player to rotate their camera when they right-click as well. I attempted this, only for the camera to spin around like crazy. This is my first building system, and I do need help with rotating the camera when right-clicking.

Local Script:

--Miscellaneous
local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera
local mouse = player:GetMouse()
local initiate = game.ReplicatedStorage.Binds.InitiateBuildMode
local garageCam = workspace.Garage.FrontEndCamera

--Services
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

--Configurations
local cameraSpeed = 0.1
local sensitivity = 100
local X = 0
local Y = 0

local function begin()
	UserInputService.InputBegan:Connect(function(input, processed)
		while wait() do
			if UserInputService:IsKeyDown(Enum.KeyCode.W) then
				camera.CFrame = camera.CFrame + camera.CFrame.LookVector * cameraSpeed
			end
					
			if UserInputService:IsKeyDown(Enum.KeyCode.S) then
				camera.CFrame = camera.CFrame + -camera.CFrame.LookVector * cameraSpeed
			end
					
			if UserInputService:IsKeyDown(Enum.KeyCode.A) then
				camera.CFrame = camera.CFrame + -camera.CFrame.RightVector * cameraSpeed
			end
					
			if UserInputService:IsKeyDown(Enum.KeyCode.D) then
				camera.CFrame = camera.CFrame + camera.CFrame.RightVector * cameraSpeed
			end
			
			if UserInputService:IsKeyDown(Enum.KeyCode.Q) then
				camera.CFrame = camera.CFrame + camera.CFrame.UpVector * cameraSpeed
			end
			
			if UserInputService:IsKeyDown(Enum.KeyCode.E) then
				camera.CFrame = camera.CFrame + -camera.CFrame.UpVector * cameraSpeed
			end
			
			if UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2) then
				local delta = input.Delta
				X = delta.X / sensitivity
				Y = delta.Y / sensitivity
            else
                X = 0
                Y = 0
			end
		end
	end)
	
	RunService:BindToRenderStep("Update", Enum.RenderPriority.Camera.Value, rotateCamera)
end

function rotateCamera()
	camera.CFrame = camera.CFrame * CFrame.Angles(Y, 0, 0) * CFrame.Angles(0, X, 0)
end

initiate.Event:Connect(begin)
1 Like