WorldToViewportPoint
This function returns the screen location and depth of a DataType/Vector3
worldPoint and whether this point is visible on the screen or not.
This function does not take in account the current GUI inset (such as the space occupied by the top bar). This means the 2D position returned is taken from the top left corner of the viewport. This means, unless you are using ScreenGui/IgnoreGuiInset
this position is not appropriate for placing GUI elements.
For an otherwise identical function that accounts for the GUI inset, see Camera/WorldToScreenPoint
.
For example:
local camera = workspace.CurrentCamera
local worldPoint = Vector3.new(0, 10, 0)
local vector, inViewport = camera:WorldToViewportPoint(worldPoint)
local viewportPoint = Vector2.new(vector.X, vector.Y)
local depth = vector.Z
Note this function does not perform any raycasting, meaning the visible bool will be true regardless if the worldPoint is obscured by BasePart|BaseParts
or Terrain
.
Parameters
Name | Type | Default | Description |
---|---|---|---|
|
The |
Returns
Return Type | Summary |
---|---|
A tuple containing, in order: A A bool indicating if the worldPoint is within the bounds of the viewport. |
Code Samples
Check if a point is visible
The following function returns true if a DataType/Vector3
is visible on screen and unobscured by BasePart|BaseParts
and Terrain
.
local function isPointVisible(worldPoint)
local camera = workspace.CurrentCamera
local vector, onScreen = camera:WorldToViewportPoint(worldPoint)
if onScreen then
local origin = camera.CFrame.p
local ray = Ray.new(origin, worldPoint - origin)
local hit = workspace:FindPartOnRay(ray)
if hit then
return false
end
else
return false
end
return true
end