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

A local sprinting script in my game is not working. I don't know what is wrong with it?

So I am making a local sprinting script to make a player go faster when they press "c". When I playtested, I the script wouldn't work. It wouldn't even print. Please help.

Code:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local walkspeed = player.CharacterAdded:Wait():WaitForChild("Humanoid").WalkSpeed	 
local replicatedstorage = game:GetService("ReplicatedStorage")
local sprinting = false

mouse.KeyDown:Connect(function(key)
	if key == "c" then
		sprinting = true
		print("sprinting")
		walkspeed = walkspeed * 2
	end
end)

mouse.KeyUp:Connect(function(key)
	if key == "c" then
		sprinting = false
		print("stopped sprinting")
		walkspeed = walkspeed / 2
	end
end)

2 answers

✓ Accepted answer

Use UserInputService instead:

local UserInputService = game:GetService("UserInputService")

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

local deb = false -- debounce
local function onKeyPress(inputObject, gameProcessedEvent)
	if not deb then
		if inputObject.KeyCode == Enum.KeyCode.C and not gameProcessedEvent then -- if the c key is pressed then
			deb = true -- to stop it from running more than once
			if player.Character and player.Character:FindFirstChild("Humanoid") then -- if the player's character and humanoid ~= nil then
				player.Character:FindFirstChild("Humanoid").WalkSpeed = player.Character:FindFirstChild("Humanoid").WalkSpeed * 2 -- give the extra walkspeed
			end
			
			repeat wait() until not UserInputService:IsKeyDown(Enum.KeyCode.C) -- wait until the C key isn't being held down anymore
			if player.Character and player.Character:FindFirstChild("Humanoid") then
				player.Character:FindFirstChild("Humanoid").WalkSpeed = player.Character:FindFirstChild("Humanoid").WalkSpeed / 2
			end
			deb = false -- setting the deb back so the function can run again
		end
	end
end

UserInputService.InputBegan:Connect(onKeyPress) -- connecting the function to InputBegan

If this answer solved your issue, please accept it! Thanks.

1 comment

1

Thank you very much

You need to use UserInputService for that.

local UIS = game:GetService'UserInputService'

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.C then
		print'C pressed!'
	end
end)

UIS.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.C then
		print'C released!'
	end
end)


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