Issue with camera rotation

I’m trying to make a cube rotate by modifying the RootJoint (Motor6D)'s C1. But I can’t get it right because, if the camera stays normally, the cube looks down. The cube stays straight only when you hold the camera actually straight which nobody does (maybe only in combat but even so, when you walk, you walk while looking down)

I’m trying to get the cube to stay straight, like this:


Unless you actually try to look down.

This is my code:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

local char = script.Parent
local torso = char:WaitForChild("Torso")
local hrp = char:WaitForChild("HumanoidRootPart")
local humanoid: Humanoid = char:WaitForChild("Humanoid")

local UpdateCubeRotation = game.ReplicatedStorage.RemoteEvents.UpdateCubeRotation

local function getmousepos()
	local includeList = workspace.InvisibleWalls:GetChildren()
	
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = includeList
	params.FilterType = Enum.RaycastFilterType.Include
	
	local result = workspace:Raycast(torso.Position, workspace.CurrentCamera.CFrame.LookVector * 10000, params)
	
	return result and result.Position or nil--mouse.Hit.Position
end

game:GetService("RunService").RenderStepped:Connect(function()
	if not plr:GetAttribute("MouseLockEnabled") then return end
	
	local mousePos = getmousepos()
	if mousePos == nil then return end
	
	local direction = (mousePos - torso.Position).unit
	local targetCFrame = CFrame.new(torso.Position, torso.Position + direction)
	local rx, ry, rz = targetCFrame:ToOrientation()
	
	local cframe = CFrame.Angles(-rx, -ry, -rz)
	
	hrp.RootJoint.C1 = cframe
	
	UpdateCubeRotation:FireServer(cframe)
end)

either the x or z axis controls the up/down rotation of the cube

depending on which one, you can clamp the rotation of the cube so that it cant go downwards

--using x as an example, could be z

rx = math.clamp(rx, 0, math.pi) -- 0 is min, pi is max

local cframe = CFrame.Angles(-rx, -ry, -rz)

Yeah X is the axis in this case, but that would look ugly if the cube can only rotate horizontally or if the cube cannot look down. I need something like a deadzone or sensitivity but idk how to implement that

Maybe try setting the rotation on X to default when the player moves using the event Humanoid.Running?

Yeah I thought of that but it looks snappy