Once you have loaded up your game, open StarterPlayer in the Explorer. If you do not see the Explorer, click on View and then click on Explorer. Inside of StarterPlayer, right click on StarterPlayerScripts, click Insert Object and insert a LocalScript.
You can delete the line of code inside of the script. To add shift to sprint to your game, we need to detect input from the user. To do this, we will be using a service called UserInputService. We will also need to include the Players service in our code so we can update the player's walk speed when the player presses the Shift key.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
We will also need to make a variable for the player object and a constant variable for the sprint speed.
local player = game.Players.LocalPlayer
local SPRINT_SPEED = 30
Next, we need to use the InputBegan event of UserInputService to detect when a player presses a key. We then need to detect if the key that the player pressed was the Shift key. If the key that the player pressed was the Shift key, then we set the player's walk speed to SPRINT_SPEED
.
UserInputService.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
player.Character.Humanoid.WalkSpeed = SPRINT_SPEED
end
end)
We also need to detect when the player lets go of the Shift key so that we can set the player's walk speed back to normal. To do this, we use the InputEnded event of UserInputService.
UserInputService.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
player.Character.Humanoid.WalkSpeed = 16
end
end)
Your entire script should look like this now:
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local player = game.Players.LocalPlayer
local SPRINT_SPEED = 30
UserInputService.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
player.Character.Humanoid.WalkSpeed = SPRINT_SPEED
end
end)
UserInputService.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
player.Character.Humanoid.WalkSpeed = 16
end
end)
One more thing we have to do is disable Shift Lock in our game, as it will interfere with the sprint system since it also uses the Shift key. To do this, click on StarterPlayer (in the Explorer window) and uncheck the EnableMouseLockOption property.
If you now play your game and hold down the Shift key, your character should sprint. Once you let go of the Shift key, your character should go back to walking at a normal speed.