Issue with projecting ray relative to viewport frame

I’m trying to project a ray, using WorldModel, from a viewport camera, relative to the mouse’s position with respect to the viewport frame. It seems as though the cutting plane given by ScreenToWorldSpace is smaller than the one given by the viewport camera. Is there something wrong with my implementation?

thread

wait(1)
local viewportFrame = script.Parent
local worldModel = viewportFrame.WorldModel

local viewportCamera = Instance.new("Camera")
viewportCamera.CameraType = Enum.CameraType.Scriptable
viewportCamera.Parent = viewportFrame

viewportFrame.CurrentCamera = viewportCamera

local dist = 50
local camPos = viewportFrame.WorldModel.PrimaryPart.Position + Vector3.new(0,dist,0)
viewportCamera.CFrame = CFrame.new(camPos, viewportFrame.WorldModel.PrimaryPart.Position)

local Mouse = game.Players.LocalPlayer:GetMouse()

local function ScreenToWorldSpace(x, y, viewportCamera)
	local viewportSize = viewportFrame.AbsoluteSize
	local viewportAspectRatio = viewportSize.X/viewportSize.Y
	local nearPlaneDepth = viewportCamera.NearPlaneZ -- (-0.5)
	local yFov = viewportCamera.FieldOfView
	local cameraPos = viewportCamera.CFrame.Position
	
	local yHalfSeg = math.abs(nearPlaneDepth*math.tan(yFov/2))
	local xHalfSeg = math.abs(yHalfSeg*viewportAspectRatio)

	local worldSpace = viewportCamera.CFrame 
	* CFrame.new(
		Vector3.new(-xHalfSeg, yHalfSeg, nearPlaneDepth)
		+ Vector3.new(2*xHalfSeg*(x/viewportSize.X), -2*yHalfSeg*(y/viewportSize.Y), 0)
	)
	
	return worldSpace.Position, (worldSpace.Position - cameraPos).Unit
end

while wait(0.1) do
	local viewportRelMousePos = Vector2.new(Mouse.X, Mouse.Y) - viewportFrame.AbsolutePosition
	
	local nearClipPos, nearClipDir = ScreenToWorldSpace(
		viewportRelMousePos.X, 
		viewportRelMousePos.Y,
		viewportCamera
	)
	
	local viewportRay = Ray.new(nearClipPos, nearClipDir*dist*1.5)
	local intersectObj, intersectPos = worldModel:FindPartOnRay(viewportRay)
	
	if intersectObj then
		local part = Instance.new("Part")
		part.Parent = viewportFrame.WorldModel
		part.Position = intersectPos
		part.Color = Color3.fromRGB(0,0,0)
		part.Size = Vector3.new(1,1,1)
		part.Anchored = true
	end
end