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

I made a script to change a characters walk speed change when they press a button. Help anyone?

local Player = game.Players.LocalPlayer

local Mouse = Player:GetMouse()
Mouse.KeyDown:connect(function(key)
	if key:byte() == 1 then
		 if game.Players.LocalPlayer.Character.Humanoid.WalkSpeed == 30 then
			game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
		elseif game.Players.LocalPlayer.Character.Humanoid.WalkSpeed == 16 then
			game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 30 
		end
	elseif key:byte() == 2 then
		 if game.Players.LocalPlayer.Character.Humanoid.WalkSpeed == 30 then
			game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
		elseif game.Players.LocalPlayer.Character.Humanoid.WalkSpeed == 16 then
			game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 30 
		end
		
	end
	
		
	end)

that is my code. I'm essentially trying to make a character run when right ctrl or left ctrl are pressed. Thanks In Advance.

1 comment

1 answer

✓ Accepted answer

Like kingdom said, using mouse for user input is deprecated. We now use UserInputService.

This uses a LocalScript in PlayerGui or StarterCharacterScripts.

local player = game.Players.LocalPlayer
repeat wait() until player.Character -- Wait until character isn't nil
local char = player.Character
local hum = char:WaitForChild("Humanoid")
local inputService = game:GetService('UserInputService') 
--  UserInputService is the new way to do anything with user input now



-- Easy way to store and check for variables is to use a table Dictionary
local keys = {
	
	['Enum.KeyCode.LeftShift'] = true;
	['Enum.KeyCode.RightShift'] = true;
	
}

inputService.InputBegan:connect(function(inputType)
	if inputType.UserInputType == Enum.UserInputType.Keyboard then 
		-- Make sure you're checking for KeyBoard input only.
		local makeKeyCodeAString = tostring(inputType.KeyCode)
		if keys[makeKeyCodeAString] then 
			local speed = hum.WalkSpeed <= 16 and 30 or 16 
			-- Ternary operator 
			-- speed is equal to this
			--[[
				if hum.WalkSpeed <= 16 then 
					speed = 30
				else
					speed = 16
				end
			--]]
			hum.WalkSpeed = speed
		end
	end
end)


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