How can I get the mouse's position in 3D space without using the Mouse object?

It says in the Wiki that UserInputService provides “wider additional functionality for interacting with the mouse” than the Mouse object, but I can’t find an alternative for the Hit property of the Mouse.

I tried doing this:

local unitray = camera:ScreenPointToRay(x, y, 0)
local ray = Ray.new(unitray.Origin, unitray.Direction * 200)
local target, position = workspace:FindPartOnRay(ray, player.Character or nil)
return position

where x and y are the coordinates from UserInputService:GetMouseLocation()

This gives a position that is near the mouse in 3D space, but not right on the cursor (as Mouse.Hit) does. How can Mouse.Hit be copied using UserInputService?

EDIT: Here’s a link to the place that shows the issue. The red ball is at the position that this function returns (which should be right on the cursor, but it’s not). https://www.roblox.com/games/59311646/

6 Likes

I’m curious as to why you do not want to use the Mouse object when it seems like the obvious option?

1 Like

I’ll probably end up using the Mouse object because it seems like way too much of a headache to use UserInputService for this, but the Wiki makes it very clear that UIS should be used instead of the Mouse - so I want to know what the expected alternative to Mouse Hit is.

6 Likes

Try using the Camera:ViewportPointToRay method, which ignores the offset that comes from the core gui.

The alternative to this would be hardcoding the offset in:

local unitray = camera:ScreenPointToRay(x, y + 36, 0)
12 Likes

Worked, thanks. Do you know why does ScreenPointToRay behaves the way it does? I can’t think of a use for it over ViewportPointToRay.

2 Likes

It’s most likely meant for use with a different part of UserInputService, mainly a connection to the UserInputService.InputChanged event to Enum.UserInputType.MouseMovement.

1 Like

Screens and viewports are different. Screen refers to the screen space you have to work with (I believe this is equivalent to the AbsoluteSize found in some Guis). Viewports are what you see for the 3D world view - essentially the proper terminology for camera.

Screen is for interface, viewport is for world view. That is why ScreenPointToRay accounts for Gui inset, while ViewportPointToRay does not.

cc @goldenstein64

6 Likes

Mouse Object dont have a method to filter descendents like a RaycastParams.

1 Like