How to convert 3D point in viewport to 2D screen position

I wanted to know how i can do this as Camera:WorldToViewportPoint() only works with the default camera, so it does not with viewports.

It should work with the viewport camera, just using viewportframe.CurrentCamera
Doing some basic testing it doesnt error or anything and gives a proper looking output

All the cameras placed previously are deleted when the game runs, including the ones in viewports, so to use this function i nee to create a new camera in the viewport, that doesn’t quite do it either as this new camera’s viewportsize proprty is always going to be 1,1 (In pixels btw), this breaks the function.
the function returns a position in offset pixels, calling it with a viewport camera returns less than 1 for each axis, whcih is not a correct scale either.

I tried using this custom function, but it does not yield correct result either:


function WorldToScreen(Creature , at)
	local viewportFrame = Creature.Adornee.Parent.Parent
	local viewportCamera = viewportFrame.CurrentCamera
	local point = viewportCamera.CoordinateFrame:pointToObjectSpace(at)
	local aspectRatio = viewportFrame.AbsoluteSize.X/viewportFrame.AbsoluteSize.Y
	local hfactor = math.tan(math.rad(viewportCamera.FieldOfView)/2)
	local wfactor = aspectRatio*hfactor
	--
	local x = (point.x/point.z) / -wfactor
	local y = (point.y/point.z) /  hfactor
	--
	return Vector2.new(viewportFrame.AbsoluteSize.X*(0.5 + 0.5*x), viewportFrame.AbsoluteSize.Y*(0.5 + 0.5*y))
end

I inputted the red cube’s position as a parameter for each time and got this result.