I’m trying to constantly get the user’s mouse location on mobile.
The issue is, Mouse.Hit only changes it’s value when UserInputService.TouchTap is fired.
I came to the solution of using Camera:ViewportPointToRay(). But unless the ray intersects with an object no position is returned.
local UserInputService = game:GetService("UserInputService")
local Camera = workspace.CurrentCamera
UserInputService.TouchMoved:Connect(function(Input)
local Position = Input.Position
local ViewportRay = Camera:ViewportPointToRay(Position.X, Position.Y)
if ViewportRay then
local RaycastResult = workspace:Raycast(ViewportRay.Origin, ViewportRay.Direction * 1000)
if RaycastResult then
--3d position is returned
else
--no 3d position is returned
end
end
end)
Was doing raycast again and had a similar issue and thought about this thread.
In my previous solution it said to use workspace:FindPartOnRay which is deprecated and was at the time so I’ve come back to provide a better solution.
Of course the ray cast returns nil, it didn’t intersect with anything what else would it return? In this script all I wanted was a 3d position so here is an updated solution that always returns a Vector3 and does not use the deprecated function
local UserInputService = game:GetService("UserInputService")
local Camera = workspace.CurrentCamera
UserInputService.TouchMoved:Connect(function(Input)
local Position = Input.Position
local ViewportRay = Camera:ViewportPointToRay(Position.X, Position.Y)
if ViewportRay then
local Direction = ViewportRay.Direction * 1000
local RaycastResult = workspace:Raycast(ViewportRay.Origin, Direction)
if RaycastResult then
return RaycastResult.Position
else
return ViewportRay.Origin * Direction
end
end
end)