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

How to fix sprint counter?

Asked by 9 years ago

Hi guys! I have a sprint script and I am trying to stop the player from being able to sprint after they have clicked shift (used it) for 20 seconds? I have tried this but have not got it working - any ideas?? Any help would be appreciated :) Thanks.

local Plr = game.Players.LocalPlayer
local Mouse = game.Players.LocalPlayer:GetMouse()
local Cam = game.Workspace.CurrentCamera
counter = 0
Mouse.KeyDown:connect(function(key)
local Key = key:lower()
if Key:byte()==48 then
Plr.Character.Humanoid.WalkSpeed = 20
for i=1, 10 do
Cam.FieldOfView = (Cam.FieldOfView + 2)
wait(0.05)
while true do
    counter = counter + 1
    wait(1)


end
end
end
end)

Mouse.KeyUp:connect(function(keyy)
local Keyy = keyy:lower()
if Keyy:byte()==48 then
Plr.Character.Humanoid.WalkSpeed = 16
for i=1, 10 do
Cam.FieldOfView = (Cam.FieldOfView - 2)
wait(0.05)
while true do
    wait(1)
    if counter == 20
        then
    end
end
end
end
end)

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

Firs thing: tab your code correctly.

The way you have things set up doesn't make any sense. You have two while true do loops that won't ever stop (because they don't have a break); in fact, a new one starts every time you press the key.


Here's a simpler way to set this up. At any given moment, the character is either sprinting or not:


--define mouse, player, etc as before sprintKey = false -- Whether or not, right now -- the sprint key is being held. Mouse.KeyUp:connect(function(key) if key:lower():byte() == 48 then sprintKey = false end end) Mouse.KeyDown:connect(function(key) if key:lower():byte() == 48 then sprintKey = true end end) while true do wait( 0.05 ) if sprintKey then Plr.Character.Humanoid.WalkSpeed = 30 else Plr.Character.Humanoid.WalkSpeed = 16 end end

Now we need to make it cost something to hold down the key. So we can do something like this:

-- use the same KeyUp/KeyDown as before

recharge = 1 -- PER SECOND
spend = 2 -- PER SECOND

maxEnergy = 20
energy = maxEnergy

while true do
    delta = wait( 0.05 ) / .05
    if energy < 0 then
        sprintKey = false
        -- Pretend they stopped pressing the button if they run out of energy.
    end

    energy = math.min(energy, maxEnergy)
    -- It can't recharge to be more than a maximum amount

    if sprintKey then
        Plr.Character.Humanoid.WalkSpeed = 30
        energy = energy - delta * spend
    else
        Plr.Character.Humanoid.WalkSpeed = 16
        energy = energy + delta * recharge
    end
end

You would, of course, also adjust FieldOfView in the place that you adjust WalkSpeed.

0
Thank you very much, but it doesn't seem to be working! I will try have and have a go at getting it to work, though! jjwood1600 215 — 9y
Ad

Answer this question