Issues using ViewportPointToRay

Hi, and thanks for reading in advance.

I made a thread the other day asking how I’d track cursor movement cross-platform sans use of the Mouse object, and one user in particular suggested that I use ViewportPointToRay to do the job - which seems to be working well enough thus far, but it doesn’t seem to be pinpoint accurate.

For visual clarity, I made the ray exactly 40 studs long and then placed a part at where the ray ends, which, if I’m not mistaken, should be right where my cursor is. Yet, unfailingly, the part always ends up slightly above my cursor. I suppose just creating an offset of some kind would be a simple fix, but exactly what would I offset? Or perhaps I’m just using this wrong?

Code (there are some things that aren’t defined here, but it shouldn’t be an issue) :

UIS.InputBegan:connect(function(input, proc)
	local t = input.UserInputType; local k = input.KeyCode

	if t == uit.MouseButton1 then
		local unitRay = cam:ViewportPointToRay(input.Position.X, input.Position.Y, 0)
		local beam = ray(unitRay.Origin, unitRay.Direction * healDistance)
				
		local hit, pos = workspace:FindPartOnRayWithIgnoreList(beam, {char, cam})
		local distance = (pos - beam.Origin).Magnitude
				
		local laser = newPart(cam, "Laser", 1, 1, 1, 0, 0, true, false)
		laser.CFrame = cfn(pos, pos + unitRay.Direction)
		laser.Material = Enum.Material.Neon
		laser.Color = rgb(255, 0, 0)
				
		game:GetService("Debris"):AddItem(laser, 1)
	end
end)

Any help or suggestions are appreciated.

you’d want to use ScreenPointToRay instead of ViewportPointToRay because ScreenPointToRay accounts for the topbar inset.

6 Likes