Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

(Re-upload) Sprinting script not working even though I followed an answer on an older post?

So, I recently got the motivation and started working on a new game I'm making. I want it to have a sprinting feature, but I can't seem to figure out what is the problem here.

I also followed a tutorial, YouTube link here: https://youtu.be/4z1HVwe0sLE

So I looked in another post in scriptinghelpers, and I found this; https://scriptinghelpers.org/questions/81021/hey-how-do-i-get-character-from-player-in-a-local-script

I followed the answer that someone posted and put it in my variables, but it still wouldn't work.

Here is the code snippet:

UserInputService = game:GetService("UserInputService")
local LShiftPressed = false
local Player = game.Players.LocalPlayer.Character
local Humanoid = Player.Humanoid

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		LShiftPressed = true
		
		while LShiftPressed == true do
			wait()
			Humanoid.WalkSpeed = 32
			game.Workspace.Sound.Sprint:Play()
		end
		
	end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		LShiftPressed = false
		
		while LShiftPressed == false do
			wait()
			Humanoid.WalkSpeed = 16
		end
		
	end
end)

Thank you if you have any feedback. Sorry if this code appears messy.

1 answer

✓ Accepted answer

Place this in StarterCharacterScripts:

--=== Services ===--

UserInputService = game:GetService("UserInputService")

--=== Variables ===--

local Player = game.Players.LocalPlayer
local Char = script.Parent
local Humanoid = Char.Humanoid

local LShiftPressed = false

--=== Hooks (Connections) ===--

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		LShiftPressed = true

		while LShiftPressed == true do
			wait()
			Humanoid.WalkSpeed = 32
			game.Workspace.Sound.Sprint:Play()
		end

		if Humanoid then
			Humanoid.WalkSpeed = 16
		end

	end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		LShiftPressed = false

		--while LShiftPressed == false do
			--wait()
			--Humanoid.WalkSpeed = 16
		--end
		-- ^^ This while loop isn't really needed

	end
end)

A good tip for variable naming is to make sure you are descriptive about what the variable represents. You had a variable Player set to the Player's character.

This discussion is preserved as it was. New answers, comments, and votes are closed.