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

ScreenPointToRay

This function creates a unit DataType/Ray from a 2D position on the screen (defined in pixels). This position accounts for the GUI inset. The DataType/Ray originates from the DataType/Vector3 equivalent of the 2D position in the world at the given depth (in studs) away from the Camera.

As this function accounts for the GUI inset, the offset applied to GUI elements (such as from the top bar) is accounted for. This means the screen position specified will start in the top left corner below the top bar. For an otherwise identical function that does not account for the GUI offset, use Camera/ViewportPointToRay.

As the DataType/Ray created is a unit ray it is only one stud long. To create a longer ray, you can do the following:

local camera = workspace.CurrentCamera
local length = 500
local unitRay = camera:ScreenPointToRay(100, 100)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * length)

Parameters

Name Type Default Description

x

The position on the X axis, in pixels, of the screen point at which to originate the DataType/Ray. This position accounts for the GUI inset

y

The position on the Y axis, in pixels, of the screen point at which to originate the DataType/Ray. This position accounts for the GUI inset

0

The depth from the Camera, in studs, from which to offset the origin of the DataType/Ray

Returns

Return Type Summary

Ray

A unit DataType/Ray, originating from the equivalent DataType/Vector3 world position of the given screen coordinates at the given depth away from the Camera. This ray is orientated in the direction of the Camera


Code Samples


Camera:ScreenPointToRay

local Camera = workspace.CurrentCamera
local Player = game:GetService("Players").LocalPlayer
local Mouse = Player:GetMouse()
 
--This will create a cube facing centered at the origin of the [[Ray]] returned and facing in the same direction. The center of the cube will be one stud in front of the camera.
Mouse.Button1Down:Connect(function()
	local ray = Camera:ScreenPointToRay(Mouse.X, Mouse.Y, 1)
    local cube = Instance.new("Part", workspace)
    cube.Size = Vector3.new(1, 1, 1)
    cube.CFrame = CFrame.new(ray.Origin, ray.Origin + ray.Direction)
    cube.Anchored = true
end)