How can you rotate CFrame's precisely?

  1. What do you want to achieve?
    I want a CFrame that points from the camera to where a pixel on the screen is “pointing” to

  2. What is the issue?
    The slide where a pixel is on the screen works as far as I know, same for how many degrees the CFrame of the camera will have to be rotated for it to point to said pixel. But when I test it with the pixel being where the mouse points and a cube that should be in the middle of it and when you just move the mouse in the X or Y axis the cube drifts off when you get to 1/4 or 3/4th of the screen and if you move in both axis it doesn’t work either.

  3. What solutions have you tried so far?
    I tried to look at the API reference, even a guide in the devhub but none really mention anything about precisely rotating a CFrame. I tried to add a piece of code to rectify some of the error but while it works on the X and Y axis, if you get a pixel on both axis it doesn’t work. I tried to split the CFrame rotation up in the different axis but that doesn’t work either. I searched up some posts on the forum, 1 mentions ScreenPointToRay but the hyperlink doesn’t work and when I search it up nothing appears

The code run in a LocalScript in a ScreenGui put in StarterGui

local Cube = Instance.new("Part")
Cube.Size = Vector3.new(2,2,2)
Cube.Anchored = true
Cube.Parent = game.Workspace

local Player = game.Players.LocalPlayer
local Camera = game.Workspace.CurrentCamera

local Mouse = Player:GetMouse()
local RunService = game:GetService("RunService")

RunService.Heartbeat:Connect(function()
	local MousePos = Vector2.new(Mouse.X/script.Parent.AbsoluteSize.X, Mouse.Y/script.Parent.AbsoluteSize.Y)
	local DegreeChange = Vector2.new(MousePos.X*Camera.MaxAxisFieldOfView-Camera.MaxAxisFieldOfView/2, MousePos.Y*Camera.FieldOfView-Camera.FieldOfView/2)
	
	--DegreeChange = DegreeChange + Vector2.new(math.sin((MousePos.X-0.5)*math.pi*2)*7,math.sin((MousePos.Y-0.5)*math.pi*2)*3)
	
	local StartFrame = Camera.CFrame
	StartFrame = StartFrame*CFrame.fromEulerAnglesXYZ(math.rad(-DegreeChange.Y), math.rad(-DegreeChange.X), 0)
	Cube.CFrame = StartFrame + StartFrame.LookVector*20
end)

The mouse cursor should be in the middle but as you can probably see, it isn’t.


2 Likes

Camera:ScreenPointToRay or Mouse.UnitRay might help solve your problem. Place the part somewhere along the Direction vector.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.