How to prevent custom camera rotation from going sideways

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to be able to fix my custom camera rotation from going sideways
  2. What is the issue? Include screenshots / videos if possible!
    It works decently but the camera rotates on the Z axis when I only change the Y and Z axis which causes the camera to go sideways sometimes.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have searched up why it rotates on that axis but I cant really find a result. I tried rotating only 1 axis and it wont go diagonal but I want to rotate for 2 axis.
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
local CameraX = workspace.CurrentCamera.CFrame.XVector.X

local CameraY = workspace.CurrentCamera.CFrame.YVector.Y

local Button2Up = false

player:GetMouse().Button2Down:Connect(function()

local X = player:GetMouse().X

local Y = player:GetMouse().Y

player:GetMouse().Button2Up:Connect(function()

Button2Up = true

end)

local Rotate = coroutine.create(function()

while true do

wait(0.05)

if Button2Up == true then

Button2Up = false

break

end

local XDist = player:GetMouse().X - X

local YDist = player:GetMouse().Y - Y

tweenservice:Create(workspace.CurrentCamera, TweenInfo.new(0.1, Enum.EasingStyle.Linear), {CFrame = CFrame.new(workspace.CurrentCamera.CFrame.Position.X, workspace.CurrentCamera.CFrame.Position.Y, workspace.CurrentCamera.CFrame.Z) * CFrame.Angles(math.rad(CameraY - YDist), math.rad(CameraX - XDist), 0)}):Play()

wait(0.05)

X = player:GetMouse().X

Y = player:GetMouse().Y

CameraX = CameraX - XDist

CameraY = CameraY - YDist

end

end)

coroutine.resume(Rotate)

end)
Code

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.