Making the rig inside the viewportframe to rotate base on y/x of the mouse location

You can write your topic however you want, but you need to answer these questions:
Im trying to achive is to make the screen into 8 diff parts and base on the y/x to rotate the rig into looking into the mouse positon ( the rig is rotating with 45* ).

- base looking

- slitly right looking ( and it started to rotate wrongly

- the problem

I looked a lot of forums and videos but i didnt found any solution to this / or how to make it correctly.

The best explanation i can do ( base on the location to rotate to the number it need ).

The script im using :

local viewportFrame = script.Parent
local rig = viewportFrame:FindFirstChild("Rig")
local userInputService = game:GetService("UserInputService")
local runService = game:GetService("RunService")
local camera = workspace.CurrentCamera

if rig then
	if not rig.PrimaryPart then
		rig.PrimaryPart = rig:FindFirstChild("HumanoidRootPart") or rig:FindFirstChild("Torso")
	end

	local function rotateBasedOnMouse()
		local mousePosition = userInputService:GetMouseLocation()
		local screenWidth = camera.ViewportSize.X
		local screenHeight = camera.ViewportSize.Y
		local centerX = screenWidth / 2
		local centerY = screenHeight / 2
		local offsetX = mousePosition.X - centerX
		local offsetY = mousePosition.Y - centerY

		print("OffsetX: " .. offsetX .. ", OffsetY: " .. offsetY)

		local rotationAngleX = math.clamp(offsetX / (screenWidth / 2), -1, 1) * 180 

		local function roundToNearestAngle(angle)
			return math.floor(angle / 45 + 0.5) * 45
		end

		rotationAngleX = roundToNearestAngle(rotationAngleX)

		local rotationAngleY = math.clamp(offsetY / (screenHeight / 2), -1, 1) * 180 
		rotationAngleY = math.clamp(rotationAngleY, -90, 90)

		if rig.PrimaryPart then
			local basePosition = rig.PrimaryPart.Position
			local newCFrame = CFrame.new(basePosition) * CFrame.Angles(0, math.rad(rotationAngleX), 0)
			rig:SetPrimaryPartCFrame(newCFrame)
		end
	end

	runService.RenderStepped:Connect(function()
		rotateBasedOnMouse()
	end)
else
	warn("Rig not found in ViewportFrame!")
end

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.