How do I get the location of a tap/click when using contextactionservice?

Hello, I am trying to detect where on screen a player taps, and after reading the documentation it seems best to use userinputservice and contextactionservice for this.

I found this code snippet in the documentation and I was planning to do something similar:

local ContextActionService = experience:GetService("ContextActionService")

local function handleAction(actionName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin then
		print(actionName, inputObject)
	end
end

-- Bind action to function
ContextActionService:BindAction("Interact", handleAction, true, Enum.KeyCode.T, Enum.KeyCode.ButtonR1)

The problem however, is that I want to know the location of the tap/click, and I don’t know how to pass that location as a parameter for the function would call.

I know i could just use something like this:

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

local function TapOrClick(position) 
	position = mouse.Hit
	print(position)
end

UserInputService.TouchTapInWorld:Connect(TapOrClick)
mouse.Button1Down:Connect(TapOrClick)

But it says in the documentation that you should use contextactionservice, and avoid using the mouse.

Thanks in advance.

1 Like

The input object should have the data as .Position or Delta.

https://developer.roblox.com/en-us/api-reference/class/InputObject

2 Likes

Thanks a lot!

Here is the finished code for everyone with a similar issue:

local ContextActionService = game:GetService("ContextActionService")

local function handleAction(actionName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin then
		print(actionName, inputObject.Position)
	end
end

-- Bind action to function
ContextActionService:BindAction("Click", handleAction, false, Enum.UserInputType.MouseButton1, Enum.UserInputType.Touch)

3 Likes