Help on ContextActionService

Hello!

I’m currently trying to learn about ContextActionService, I want to know where I could put this in the script when it is needed, right now I have a mobile button that works but dosen’t fit every mobile device.

Here is the script:

-- Variables
local userInputService = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()

-- Variables for Stamina
local isSprinting = false
local maxStamina = 500
local stamina = maxStamina

local sprintBar = script.Parent:WaitForChild("StaminaBar")
local staminaButton = script.Parent:WaitForChild("SprintButton")

-- Function
local function sprint(SType)
	local humanoid = char:FindFirstChild("Humanoid")
	
	if SType == "Began" then
		isSprinting = true
		humanoid.WalkSpeed = 32
	elseif SType == "Ended" then
			isSprinting = false
			humanoid.WalkSpeed = 12
	end
end

-- Check if Player is on Mobile
if userInputService.TouchEnabled then
	staminaButton.Visible = true
end

-- If player is on PC
userInputService.InputBegan:Connect(function(input, process)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		sprint("Began")
	end
end)

userInputService.InputEnded:Connect(function(input, process)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		sprint("Ended")
	end
end)

-- Mobile Controls
staminaButton.MouseButton1Down:Connect(function()
	sprint("Began")
end)

staminaButton.MouseButton1Up:Connect(function()
	sprint("Ended")
end)

game:GetService("RunService").RenderStepped:Connect(function()
	local humanoid = char:FindFirstChild("Humanoid")
	
	if stamina == 0 and isSprinting then
		sprint("Ended")
	end
	
	if isSprinting and humanoid.MoveDirection.Magnitude > 0 then
		stamina = stamina - 1 -- Run
	else
		stamina = stamina + 4 -- Rest
	end
	
	stamina = math.clamp(stamina, 0, maxStamina)
	sprintBar.SprintFrame.Size = UDim2.new(stamina/maxStamina, 0, 1, 0)
end)

I want to know where I could use this in the script instead of using a button, I also have tried a line of code to test how it would work, but the button is very small and dosen’t fit with the Roblox mobile UI (Jump button). I am still learning about this and is still a beginner at developing games.

How can i do this?

try to combine your other functions into one and put this at the end

game:GetService('ContextActionService'):BindAction('RunMobileTest', sprint, true, Enum.KeyCode.LeftShift)
1 Like