Make click detection system work both for mobile and pc

I have a system that requiers the object a player clicked on, I know how to do this both on mobile and on pc, however I need one way that works for both. I have searched on the forums, found some things but nothing seems to be just the right thing.

To do it on mobile I’d use:

UIS.TouchTapInWorld:Connect(function(vector2Pos,ProcessedByUI)
	if not ProcessedByUI then
		if mouse.Target then
			local targetObject = mouse.Target
		end
	end
end)

And for pc simply:

mouse.Button1Down:Connect(function()
	local targetObject = mouse.Target
end)

The problem with using the pc method on mobile aswell, is that it gets the previously touched position and not the new one… if I want a thing to happen on a specific clicked object, I’d have to click it twice basically.
And the problem with using the mobile method on pc is that it simply doesn’t work since TouchTapInWorld isn’t a thing on pc.
How would I simply get the actual clicked part, using a method that works for all users.

2 Likes

Have you considered using ClickDetectors or ProximityPrompts?

1 Like

Oh I forgot to mention that, I am looking for a way to get any object that is clicked on, not specific objects with click detectors.

1 Like

One solution might be to use both methods.


local inCooldown = false

function setTargetObj()
	if inCooldown then return end
	inCooldown = true

	local targetObject = mouse.Target
	-- do stuff

	wait(.1)
	inCooldown = false
end

UIS.TouchTapInWorld:Connect(function(vector2Pos,ProcessedByUI)
	if not ProcessedByUI then
		if mouse.Target then
			--local targetObject = mouse.Target
			setTargetObj()
		end
	end
end)

mouse.Button1Down:Connect(function()
	--local targetObject = mouse.Target
	setTargetObj()
end)

untested code
there might be a more optimal solution out there
on the other hand, some laptops have touch screen, so doing this anyway might be a good idea

1 Like

I appreciate your answer, but I ended up finding another way to solve my issue!
Basically all I had to do is:

local function onInputBegan(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
		if not gameProcessed then
			if mouse.Target then
				local targetObject = mouse.Target
			end
		end
	end
end)

UIS.InputBegan:Connect(onInputBegan)

The fact that I didn’t think about this is kind of dumb but it is what it is :grinning_face_with_smiling_eyes:

4 Likes

oh yeah i totally forgot about that event

problem with this is that if a player right clicks it will also active this

1 Like

No, because theres no detection for MouseButton2 and Touch won’t get detected with regular mouse