A function to get a cursor's position in 3d space

Since Mouse is depreciated, I thought I’d post the function I use to get mouse positions in 3d space for my guns and other silly systems.


local RaycastParameters = RaycastParams.new()
RaycastParemeters.FilterType = Enum.RaycastFilterType.Exclude
RaycastParemeters.FilterDescendantsInstances = {} -- add anything you want ignored here.

local Distance = 1000 -- can be set to any number.

function CursorToPosition()
     local MousePosition= UserInputService:GetMouseLocation()
     local UnitRay= Camera:ViewportPointToRay(MousePosition.x, MousePosition.y)

     return workspace:Raycast(UnitRay.Origin, UnitRay.Direction * Distance, RaycastParameters)
end
8 Likes

Hi! This is almost working. I was facing some glitches with this, so here’s a fixed version:

You simply add UnitRay.Origin to the Direction, because otherwise the final Direction Position is as if it were coming from Coordinates 0,0,0 - the null point.

local RaycastParameters = RaycastParams.new()
RaycastParemeters.FilterType = Enum.RaycastFilterType.Exclude
RaycastParemeters.FilterDescendantsInstances = {} -- add anything you want ignored here.

local Distance = 1000 -- can be set to any number.

function CursorToPosition()
     local MousePosition= UserInputService:GetMouseLocation()
     local UnitRay= Camera:ViewportPointToRay(MousePosition.x, MousePosition.y)

     return workspace:Raycast(UnitRay.Origin, UnitRay.Origin + UnitRay.Direction * Distance, RaycastParameters)
end
2 Likes

Adding the Origin alters the projection of the mouse position by the camera position. The direction itself does not care about the origin. A vector of (0, -1, 0) will always point down, regardless of what the origin of the raycast is. I’m glad this fixed whatever issue you had, but it’s a fix to your issue, it isn’t something incorrect in the original code itself.

1 Like