Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I fix my Shift to Sprint so it works with Shift Lock too?

Asked by
c4ots 12
3 years ago

It doesnt work if Shift Lock is enabled, its a Local Script in StarterGUI folder. Thank you in advance! This is the script:

local player = game.Players.LocalPlayer

local mouse = player:GetMouse()

local sprintSpeed = 40

mouse.KeyDown:Connect(function(key)

if key == "0" then

    --Sprint

    player.Character.Humanoid.WalkSpeed = sprintSpeed

end

end)

mouse.KeyUp:Connect(function(key)

if key == "0" then

    --Stop Sprint

    player.Character.Humanoid.WalkSpeed = 16

end

end)

1 answer

Log in to vote
0
Answered by 3 years ago

Hello,

Your method of getting the player's keyboard input is deprecated, it's good practice to use UserInputService instead.

UserInputService has a better system for processing keyboard inputs than mouse.KeyDown does. While mouse.KeyDown's inputs are processed by a single string, UserInputService allows us to see the exact key being pressed. This means that special characters like "Shift" and "Tab" will not be defaulted to "0", and coincidentally, will allow your code to work while shift lock is enabled.

Here's an implementation of UserInputService for your code:

local uis = game:GetService("UserInputService") --get userinputservice
local sprintspeed = 40

local player = game:GetService("Players").LocalPlayer --better way of setting localplayer
local character = workspace:WaitForChild(player.Name) --wait for player's character to be created (there is buffer between player joining and character being created)
local humanoid = character.Humanoid -- assign humanoid

uis.InputBegan:Connect(function(key)
    if key.KeyCode == Enum.KeyCode.LeftShift then
        humanoid.WalkSpeed = sprintspeed
    end
end)

uis.InputEnded:Connect(function(key)
    if key.KeyCode == Enum.KeyCode.LeftShift then
        humanoid.WalkSpeed = 16
    end
end)

This code will work with shift lock.

Another thing to add is the ability to disable shift lock as a developer. If you desire, you can go to StarterPlayer under your explorer window, navigate to your properties window, and disable "EnableMouseLockOption". This will automatically disable shift lock for ALL players of your game.

I hope this answer helped you!

Cheers,

Chase

0
Hi! I can't really understand UserInputService, is it something I have to add or is it a folder to put Scripts in? Where should I put the script (i tried in StarterGui but doesn't seem to work)? I am a noob at this, sorry and thank you SO MUCH! c4ots 12 — 3y
0
Put the script in "StarterPlayerScripts" and no you don't have to add userinputservice, externally... it's similar to getmouse :) NinjaManChase 226 — 3y
0
THANK YOU!! IT WORKS, YOU'RE THE BEST!!!!!!! c4ots 12 — 3y
0
Of course! Glad to help you out! NinjaManChase 226 — 3y
Ad

Answer this question