Help making a Vector2 to Vector3 Function

hi, im looking for a function which i cant really find anything on. I want to achieve a Vector2 to Vector3 function.

Im hoping it can operate close to how the mouse works (mouse x and y are converted to mouse.hit.position)

i have absolutely zero idea how im going to go about this, so im coming here for help

1 Like

https://developer.roblox.com/en-us/api-reference/function/Camera/ViewportPointToRay

https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast

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)
1 Like

Vector2 is the X and Y of Vector3 so I don’t really understand what you mean.

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...

some rounding needed of course

1 Like