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

So... Here is my sprint script it is somehow working buti feel like that it can be better?

Asked by 6 years ago
Edited 6 years ago
local mouse = game.Players.LocalPlayer:GetMouse()
local running = false

function getTool()  
    for _, kid in ipairs(script.Parent:GetChildren()) do
        if kid.className == "Tool" then return kid end
    end
    return nil
end


mouse.KeyDown:connect(function (key) -- Run function
    key = string.lower(key)
    if string.byte(key) == 48 then
        running = true
        local keyConnection = mouse.KeyUp:connect(function (key)
            if string.byte(key) == 48 then
                running = false
            end
        end)
        game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = game.Players.LocalPlayer.Stats.Agility.Value + 30
        repeat wait () until running == false or game.Players.LocalPlayer.Stamina.Value <= 0
        keyConnection:disconnect()
        game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
    end
end)

mouse.KeyDown:connect(function (key)
    key = string.lower(key)
    if string.byte(key) == 48 then
        running = true
        while running == true and game.Players.LocalPlayer.Stamina.Value > 0 do
            game.Players.LocalPlayer.Stamina.Value = game.Players.LocalPlayer.Stamina.Value-2
            print("Gay")
            if game.Players.LocalPlayer.Stamina.Value <= 2 then
                game.Players.LocalPlayer.Stamina.Value = 0
            end
            wait(0.1)
        end
        running = false
    end
end)

It sprints based on player's agility and drains the player's stamina by 2 every 1/10th of a second(second block of code)

Experimented until it worked, but I have a strong feeling that there will be a bug somewhere and it can be improved

0
You shouldn’t be using KeyDown. User#19524 175 — 6y

1 answer

Log in to vote
2
Answered by 6 years ago
Edited 6 years ago

There won’t be a bug, but you shouldn’t be using KeyDown to get user input. It’s deprecated and just so inefficient. Instead, use UserInputService.InputBegan.

local userInputService = game:GetService"UserInputService"
local plr = game:GetService"Players".LocalPlayer

userInputService.InputBegan:Connect(function(key, chatting)
    if chatting then
        return
    end

    if key.KeyCode == Enum.KeyCode.LeftShift then
        plr.Character.Humanoid.WalkSpeed = 24 -- set to desired speed
    end
end)

userInputService.InputEnded:Connect(function(key, chatting)
    if chatting then
        return
    end

    if key.KeyCode == Enum.KeyCode.LeftShift then
        plr.Character.Humanoid.WalkSpeed = 16
    end
end)
0
Should be InputEnded for the second one. mattscy 3725 — 6y
0
forgot lol User#19524 175 — 6y
0
Thanks, modified the script a little bit to make it drain stamina and stop on stamina. Thanks xD xxXTimeXxx 101 — 6y
Ad

Answer this question