Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I use :ViewportPointToRay() Depth correctly?

Asked by
rexhawk 222 Moderation Voter
4 years ago

Hello,

Since the integration of mobile compatibility to my first person game, I've had to change some things, including the way the game gets the part the player is looking at, to display a tooltip if that part is recognized as an interactable part.

Previously, I simply locked the player's mouse in the center of the screen, and used Mouse.Target to get the part the player was looking at. When I added mobile compatibility, I could no longer do that because the mouse would move to wherever the player taps, breaking the game.

This was a big issue, so I researched a bit and found Camera:ViewportPointToRay(). Because it let me get the part that is in the center of the screen, working on both platforms, and was effective at that. But I'm not experienced with this and this caused issues. Mainly the Depth variable in it.

My code:

local function getMouseTarget()
    local ray = workSpace.CurrentCamera:ViewportPointToRay(coreGui.CursorPoint.AbsolutePosition.X, coreGui.CursorPoint.AbsolutePosition.Y, 1)
    ray = Ray.new(ray.Origin, ray.Direction * 999)
    return workSpace:FindPartOnRay(ray)
end

You see, when I set to depth variable to 1, it works semi-well with the door, but it doesn't work when I look down... Example I looked into this and discovered the depth variable was the culprit. I tried switching to depth variable to 5, and it fixed the problem, but created a new one, because now I need to be standing about 5 studs away for it to be detected.

So my question is, how do I properly use the Depth variable to make this act like Mouse.Target?

1 answer

Log in to vote
0
Answered by
Nowaha 459 Moderation Voter
4 years ago
Edited 4 years ago

Hi rexhawk,

Try using Camera#ScreenPointToRay() instead of Camera#ViewportPointToRay(). You should be able to just remove the ,1 and it'll work;

local function getMouseTarget()
    local ray = workspace.CurrentCamera:ScreenPointToRay(coreGui.CursorPoint.AbsolutePosition.X, coreGui.CursorPoint.AbsolutePosition.Y)
    ray = Ray.new(ray.Origin, ray.Direction * 999)
    return workspace:FindPartOnRay(ray)
end
0
If this does not work, just put 0 instead of 1 as depth. Nowaha 459 — 4y
Ad

Answer this question