Raycasting to Tap Position on Mobile?

Hey :smiley: I’ve tried to use TouchTapInWorld and use the first parameter to create a ray by putting it in :ViewportPointToRay() but that keeps returning nil. This is the script that I’ve created

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local uis = game:GetService("UserInputService")
local camera = game.Workspace.CurrentCamera
local filter = {}

uis.TouchTapInWorld:Connect(function(arg1, arg2)
        local ray = camera:ViewportPointToRay(arg1.X, arg1.Y , 900)
        local target, point, surface = game.Workspace:FindPartOnRayWithIgnoreList(ray, filter)
        print(target)
end)

I cannot use mouse.Target because I need a TargetFilter with more than 1 object to ignore.

1 Like

You have to change the arguments to ViewportPointToRay and extend the resulting ray. The extra argument to the function is creating the ray 900 studs in front of the camera, and the ray is too short to detect anything:

local Workspace = game:GetService("Workspace")

local selectParams = RaycastParams.new()

uis.TouchTapInWorld:Connect(function(position, processed)

	-- create a unit ray, 0 studs in front of the camera
	local ray = camera:ViewportPointToRay(position.X, position.Y, 0)

	-- cast ray
	local result = Workspace:Raycast(
        ray.Origin, 
        ray.Direction * 500, -- make ray 500 studs long, 5000 is max
        selectParams
    )

    if result then
	    print(result.Instance)
    end
end
7 Likes