local Camera = workspace.CurrentCamera
local length = 500 --ray length(max distance of detectable parts)
local x, y = 500, 200 --screen coordinates
--Instances created just for the sake of visualizing the 3d position
local ignore = Instance.new("Folder", workspace)
local part = Instance.new("Part", ignore)
part.Anchored = true
function to3d(x, y)
local unit = Camera:ScreenPointToRay(x, y)
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {ignore}
local result = workspace:Raycast(unit.Origin, unit.Direction*length, params)
return result.Position
end
game:GetService("RunService").RenderStepped:Connect(function()
local pos = to3d(x, y)
part.Position = pos
end)
Sorry for the late reply, hopefully, this helps someone!
Introduction
If you want the “inverse” of the Camera:WorldToViewportPoint function, you would use ViewportPointToRay function. The origin of this ray is the input of Camera:WorldToViewportPoint.
Converting Vector2 → Vector3
local CurrentCamera = workspace.CurrentCamera
local Target2 = Vector2.new(500, 600)
local Target3 = CurrentCamera:ViewportPointToRay(Target2.X, Target2.Y, 0).Origin
local Target2_2 = CurrentCamera:WorldToViewportPoint(Target3)
print(Target2) -- 500, 600
print(Target3) -- 26.505..., 17.700..., 35.551...
print(Target2_2) -- 500.012..., 600.013..., 0.100...