Getting XYZ position from a touch tap on mobile

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

In my game a player clicks their mouse (or taps their mobile screen) to move an object to a precise position by using the command CFrame.new(position).

  1. What is the issue? Include screenshots / videos if possible!

It works fine on a desktop computer (my use of mouse.Hit.p yields an X,Y,Z position and the CFrame of the object is moved to the correct XYZ location), but on mobile it doesn’t work (my use of TouchTap yields only a X and Y position and the object doesn’t move because the code is expecting XY and Z coordinates for the CFrame.new command).

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I read as many articles as I could and tried to reference this article in particular: UserInputService.TouchTap

Please see code for desktop (which works) and mobile (which doesn’t work)

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local player = game.Players.LocalPlayer
local UserInputService = game:GetService("UserInputService")

if (UserInputService.KeyboardEnabled) then
	local mouse = player:GetMouse()
	position = mouse.Hit.p
else
        local function TouchTap(touchPosition, gameProcessedEvent)
	       position = Vector2.new(touchPosition[1].X, touchPosition[1].Y)
        end

	if UserInputService.TouchEnabled then
		UserInputService.TouchTap:Connect(TouchTap)
	end

end

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

You can use mouse.Hit.p on mobile too.

This UserInputService event may help:
https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchTapInWorld

If you scroll down a bit on that page, the Code Samples section conveniently has exactly what you’re looking for – finding a 3D position from a screen tap.

It uses the Camera function VectorPointToRay to create a Unit Vector from the tap position on screen, and Raycasts in that direction to find the position in the world.

1 Like