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

How to change the key?

I created this script following some instructions but I am not sure how I would change it so that if the F key is hit you sprint but if the F key is hit again you stop sprinting. I also would like an explanation as to how this script exactly works as I see this string stuff and and I am not sure what it even does.

--Put in Game.StarterPlayer.StarterPlayerScripts

local player = game.Players.LocalPlayer
repeat wait() until player.Character
local character = player.Character
local mouse = player:GetMouse()

LastTap = math.floor(tick())

mouse.KeyDown:connect(function(key)
	key = key:lower()
	if key == string.char(48) then
	character.Humanoid.WalkSpeed = 30
			
		end
	end
)

mouse.KeyUp:connect(function(key)
	key = key:lower()
	if key == string.char(48) then
		character.Humanoid.WalkSpeed = 16
	end
end)

1 answer

✓ Accepted answer

My first suggestion would be to use the UserInputService since KeyDown and KeyUp are deprecated methods of getting user input.

With that in mind there are two events we need in the UserInputService:

http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputBegan http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputEnded

The first event, InputBegan, fires when the user presses a key down or their mouse up. The second event, InputEnded, fires when the user stops pressing a key down or up.

These events also give us something called input objects:

http://wiki.roblox.com/index.php?title=API:Class/InputObject

One of their properties is the KeyCode property:

http://wiki.roblox.com/index.php?title=API:Class/InputObject/KeyCode

It returns an enum of the key pressed (assuming it exists otherwise nil). The enum list can be found here: http://wiki.roblox.com/index.php?title=API:Enum/KeyCode remeber though, intellisense is a life saver sometimes.

That being said, we have a enough information now to solve your problem.

local player = game:GetService("Players").LocalPlayer;
local character; repeat wait(); character = player.Character; until character;
local humanoid = character:WaitForChild("Humanoid");

local inputService = game:GetService("UserInputService");

inputService.InputBegan:connect(function(input, process)
	if process then return; end; -- don't continue if player is in menu or something
	if input.KeyCode == Enum.KeyCode.LeftShift then -- player pressed the leftshift key
		humanoid.WalkSpeed = 30;
	end;
end);

inputService.InputEnded:connect(function(input, process)
	-- same process as above but when the player stops pressing the key
	if input.KeyCode == Enum.KeyCode.LeftShift then
		humanoid.WalkSpeed = 16;
	end;
end);

1 comment

0

Thanks! What would the code be though if I wanted to use the F key?

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