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

A local sprinting script in my game is not working. I don't know what is wrong with it?

Asked by 4 years ago

So I am making a local sprinting script to make a player go faster when they press "c". When I playtested, I the script wouldn't work. It wouldn't even print. Please help.

Code:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local walkspeed = player.CharacterAdded:Wait():WaitForChild("Humanoid").WalkSpeed    
local replicatedstorage = game:GetService("ReplicatedStorage")
local sprinting = false

mouse.KeyDown:Connect(function(key)
    if key == "c" then
        sprinting = true
        print("sprinting")
        walkspeed = walkspeed * 2
    end
end)

mouse.KeyUp:Connect(function(key)
    if key == "c" then
        sprinting = false
        print("stopped sprinting")
        walkspeed = walkspeed / 2
    end
end)

2 answers

Log in to vote
0
Answered by 4 years ago

Use UserInputService instead:

local UserInputService = game:GetService("UserInputService")

local Players = game:GetService("Players")
local player = Players.LocalPlayer

local deb = false -- debounce
local function onKeyPress(inputObject, gameProcessedEvent)
    if not deb then
        if inputObject.KeyCode == Enum.KeyCode.C and not gameProcessedEvent then -- if the c key is pressed then
            deb = true -- to stop it from running more than once
            if player.Character and player.Character:FindFirstChild("Humanoid") then -- if the player's character and humanoid ~= nil then
                player.Character:FindFirstChild("Humanoid").WalkSpeed = player.Character:FindFirstChild("Humanoid").WalkSpeed * 2 -- give the extra walkspeed
            end

            repeat wait() until not UserInputService:IsKeyDown(Enum.KeyCode.C) -- wait until the C key isn't being held down anymore
            if player.Character and player.Character:FindFirstChild("Humanoid") then
                player.Character:FindFirstChild("Humanoid").WalkSpeed = player.Character:FindFirstChild("Humanoid").WalkSpeed / 2
            end
            deb = false -- setting the deb back so the function can run again
        end
    end
end

UserInputService.InputBegan:Connect(onKeyPress) -- connecting the function to InputBegan

If this answer solved your issue, please accept it! Thanks.

1
Thank you very much R0B0T_K1LLER 0 — 4y
Ad
Log in to vote
0
Answered by
Asceylos 562 Moderation Voter
4 years ago

You need to use UserInputService for that.

local UIS = game:GetService'UserInputService'

UIS.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.C then
        print'C pressed!'
    end
end)

UIS.InputEnded:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.C then
        print'C released!'
    end
end)


Answer this question