Sprint button not working as I want

Hey, so I made a mobile sprint button and it works but you have to hold it while moving to sprint. Instead I want it to make you sprint once you tap the sprint button and once you press it again it unsprints


local userInput = game:GetService("UserInputService")

local players = game:GetService("Players")



local sprintSpeed = 24

local walkSpeed = 16 



local player = players.LocalPlayer



local function beginSprint(input, gameProcessed)

    if not gameProcessed then        

        if input.UserInputType == Enum.UserInputType.Keyboard then

            local keycode = input.KeyCode

            if keycode == Enum.KeyCode.C then 

                player.Character.Humanoid.WalkSpeed = sprintSpeed

            end

        end

    end

end



local function endSprint(input, gameProcessed)

    if not gameProcessed then

        if input.UserInputType == Enum.UserInputType.Keyboard then

            local keycode = input.KeyCode

            if keycode == Enum.KeyCode.LeftControl then

                player.Character.Humanoid.WalkSpeed = walkSpeed

            end

        end

    end

end



userInput.InputBegan:Connect(beginSprint)

userInput.InputEnded:Connect(endSprint)

1 Like

Instead of using two UIS events to detect when the button is held and released, you can use one to detect when its pressed, then change a bool to the opposite of what it is currently.

Pressing it once would change it to true, pressing it against would change it to false.
(Not the best explanation but it works)

Try something like this:

local button = script.Parent -- Change to where the button is located

local players = game:GetService("Players")

local sprintSpeed = 24

local walkSpeed = 16 

local player = players.LocalPlayer

local IsSprinting = false -- This will be used to detect if the player is sprinting or not

local function ToggleSprint()
	if IsSprinting == false then -- Checks if the player is sprinting
		player.Character.Humanoid.WalkSpeed = sprintSpeed -- Sets the walkspeed to sprinting
		IsSprinting = true -- Changes the IsSprinting var to true
		print("Player is sprinting")
	else -- If the player is not sprinting
		player.Character.Humanoid.WalkSpeed = walkSpeed -- sets the walkspeed to normal
		IsSprinting = false -- Changes the IsSprinting var to false
		print("Player is not sprinting")
	end
end

button.TouchTap:Connect(ToggleSprint) -- Detects when the button is tapped
button.MouseButton1Click:Connect(ToggleSprint) -- Optional (Detects when a mouse clicks it)

Place this in a local script in a gui button (Text button or Image button)

Let me know if it doesn’t work.

EDIT:

You could mix this with Remote Events to change the walkspeed on the server side instead of the client (Although there wouldn’t be much of a difference as it still works as expected. Either way, I still recommend it) .