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

[SOLVED] Tell if a user is holding down a key then make the players speed faster if they are?

I've been trying to make it so if the player continues to hold down left shift, there speed will continuously increase. Just can't seem to get it to work. If I hold down left shift the playerSprintSpeed stays the same, even though when i'm printing the speed it goes up. I'm a total noob when it comes to roblox scripting so any help is appreciated. Thanks!

local player = game:GetService("Players").LocalPlayer
local character = player.Character
local UserInputService = game:GetService("UserInputService")
local defaultSpeed = 16
local leftShift = Enum.KeyCode.LeftShift
local leftShiftDown = false
local playerSprintSpeed = 16

UserInputService.InputBegan:Connect(function(key)
	if key.KeyCode == leftShift then
		character.Humanoid.WalkSpeed = playerSprintSpeed
		leftShiftDown = true
	end
end)

UserInputService.InputEnded:Connect(function(key)
	if key.KeyCode == leftShift then
		character.Humanoid.WalkSpeed = defaultSpeed
		print(character.Humanoid.WalkSpeed)
	end
end)

while wait() do
	if leftShiftDown then
		print("yes...")
		playerSprintSpeed = playerSprintSpeed + 1
		print(playerSprintSpeed)
	else
		print("no...")
	end
end

3 comments

0

Once the press shift, it will continuously say yes, cause you never made "leftShiftDown" false again

0

Your while loop should be within your InputBegan function.

0

Also, playerSprintSpeed is 16

1 answer

It's because your "playerSprintSpeed" is 16, the same as "defaultSpeed". Though I think something like this would work better

local uis = game:GetService('UserInputService')
local plr = game.Players.LocalPlayer
repeat wait() until plr.Character
local playerSprintSpeed = 32
local defaultSpeed = 16

while wait() do
	if uis:IsKeyDown(Enum.KeyCode.LeftShift) then
		plr.Character.Humanoid.WalkSpeed = playerSprintSpeed
	else
		plr.Character.Humanoid.WalkSpeed = defaultSpeed
	end
end

5 comments

0

Bro thanks a lot now it's working!

0

np

0

Where did you learn how to script? I've just been watching a lot of tutorials on yt and just reading the roblox documentation

0

I started out watching tutorials on how to script certain things and since I already knew Python, I just picked it up. I never really watched any Lua tutorials

0

Cool cool man. Thanks again!

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