PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

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 DataType/Vector3 world position

Returns

Return Type Summary

A tuple containing, in order:

A DataType/Vector3 whose X and Y components represent the offset of the worldPoint from the top left corner of the viewport, in pixels. The DataType/Vector3|Vector3’s Z component represents the depth of the worldPoint from the screen (in studs).

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