How would I go about making a custom ViewportPointToRay function?

  1. What do you want to achieve? Keep it simple and clear!
    I want to achieve the same functionality as CurrentCamera:ViewportPointToRay but as a separate function. The reason I need this is that I need the flexibility to change the way it works.

  2. What is the issue? Include screenshots / videos if possible!
    The issue is that I have absolutely no idea how to approach this. I already had to seek help devising a custom function for WorldToViewportPoint (NearPlaneZ is not correct for cameras other than CurrentCamera - #2 by programeow)

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve already tried several methods, like getting the XY viewport point coordinate as a -1 to 1 value depending on the position of the point (where the center of the screen is 0, 0) and using that to construct a new CFrame angle, multiplied to the camera CFrame, and using the LookVector as a Direction argument for the returned Ray, but the result is an inaccurate representation when the viewport point is in between the center of the screen and either side of it.

Here is what I have so far, which is the one that has the inaccuracy between edges vs the center of the screen.

function module:ViewportPointToRay(viewportPoint: Vector2, depth: number?, camera: (Camera | {ViewportSize: Vector2, FieldOfView: number, CFrame: CFrame})?)
	if (typeof(viewportPoint) == "Vector2") then
		local ViewportSize, FieldOfView, CoordinateFrame =
			if ((typeof(camera) == "Instance" and camera:IsA("Camera")) or (typeof(camera) == "table" and typeof(camera.ViewportSize) == "Vector2")) then camera.ViewportSize elseif (CurrentCamera) then CurrentCamera.ViewportSize else Vector2.new(1, 1),
			if ((typeof(camera) == "Instance" and camera:IsA("Camera")) or (typeof(camera) == "table" and typeof(camera.FieldOfView) == "number")) then camera.FieldOfView elseif (CurrentCamera) then CurrentCamera.FieldOfView else 70,
			if ((typeof(camera) == "Instance" and camera:IsA("Camera")) or (typeof(camera) == "table" and typeof(camera.CFrame) == "CFrame")) then camera.CFrame elseif (CurrentCamera) then CurrentCamera.CFrame else CFrame.new(0, 20, 20) * CFrame.fromOrientation(-math.pi/4, 0, 0)
		
		local focalLength = self:GetFocalLength(FieldOfView)
		local x, y = 2 * viewportPoint.X/ViewportSize.X - 1, 2 * viewportPoint.Y/ViewportSize.Y - 1
		local direction = (CoordinateFrame * CFrame.fromOrientation(math.rad((CurrentCamera.FieldOfView/2) * -y), math.rad((CurrentCamera.MaxAxisFieldOfView/2) * -x), 0)).LookVector
		return Ray.new(CoordinateFrame.Position + (direction * if (typeof(depth) == "number") then depth else 0), direction)
	end
end

I would really appreciate any lead I can get, as this is doing my head in from every angle. Thank you!