Gain speed when pressing a keyboard key

So, I know this is really easy but I’m trying to make it so when a player presses the button Q or ctrl they gain a short boost of speed that goes away. I already have the key detecting part but I don’t know how to change the speed of the player. And I’m guessing that it needs to be in a local script. Here is the detecting of the key being pressed.

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.LeftControl then
		
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)

image

local hasspeed = false

function onKeyPress(inputObject, gameProcessedEvent)
        if gameProcessedEvent then return end
	if inputObject.KeyCode == Enum.KeyCode.LeftControl then
		if not hasspeed then
                        hasspeed = true
                         local oldSpeed =  localCharacter.Humanoid.WalkSpeed
                        localCharacter.Humanoid.WalkSpeed = 100
                        wait(10)
                             localCharacter.Humanoid.WalkSpeed = oldSpeed
                        hasspeed = false
               end
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)
1 Like

What do I define localCharacter as because it doesn’t look like you did it.

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local hasSpeed = false

local function onKeyPress(inputObject, gameProcessedEvent)
    if gameProcessedEvent then return end
	if inputObject.KeyCode == Enum.KeyCode.LeftControl then
		if not hasSpeed then
        	hasSpeed = true
        	local oldSpeed = character.Humanoid.WalkSpeed
        	character.Humanoid.WalkSpeed = 100 -- How fast the player becomes
       	 	wait(10) -- How long the player has extra speed for
			character.Humanoid.WalkSpeed = oldSpeed
			wait(5) -- How long until they can use the boost again
        	hasSpeed = false
        end
	end
end

game:GetService("UserInputService").InputBegan:Connect(onKeyPress)

2 Likes

I believe there is a error with the script because I tested it with pressing left control and E, I also added a print to see if the key was pressed and nothing popped up in the output

Is there anything else in the script? Where’s the script at? It worked fine when I tested it.

I put it in server script service and I also tried putting it in the workspace.

LocalScripts will not function when placed in either of those places.

https://developer.roblox.com/en-us/api-reference/class/LocalScript

1 Like

Put it in StarterPlayer>StarterCharacterScripts. This way, it’ll actually work and continue to once you respawn.

Thank you for your help.

30 chars