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

How to add a delay in between gunshots?

Asked by 4 years ago
Edited 4 years ago

So I've made a framework for my game that I've been updating recently in order to accommodate more mechanics such rest animations, shooting animations, etc. What I'm trying to figure out is how to make it so when a player fires a shot they have to wait a certain amount of time in order to fire again. I'm relatively new to scripting.

Code used:

--//Shooting Animation Segment
script.Parent.Activated:Connect(function(onMouseClick)
    local shooting = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Shoot)
    local sound = game.StarterPack.Pistol.Sound
    sound:Play()
    shooting:Play()
    wait(1)
end)

(Sound does not play for other players, only for the player using the tool, but that's a bit unrelated.)

If somebody could tell me my error or give me tips on how to fix it I'd greatly appreciate it.

2 answers

Log in to vote
1
Answered by 4 years ago

Hi littlekit,

In this case you need to use a debounce. Debounces can make your script have a 'cooldown period.' It just uses a boolean to test whether the function can run again. In basic terms, think of it like a gate that opens and closes. It looks like this:

local debounce = true;

function fire()
    if debounce then
        debounce = false -- Shut the door so function doesn't run until debounce is true.

        -- All of your code goes in here.
        wait(2)
        debounce = true -- Open the door for function to run.
    end
end

Go here to find out more about debounces.

Thanks,

Best regards,

Idealist Developer

0
Thanks alot! This is going to help in the framework. littlekit07 16 — 4y
0
Glad to help :) IdealistDeveloper 234 — 4y
Ad
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

You have to use a debounce, commonly known as a cooldown. Try this:

local debounce = false

local cooldownTime = 1

script.Parent.Activated:Connect(function() 
    if not debounce then
        debounce = true
        local shooting = game:GetService("Players").LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Shoot)

        local sound = game:GetService("StarterPack").Pistol.Sound

        sound:Play()
        shooting:Play()
        wait(cooldownTime)
        debounce = false
    end
end)

The if statement checks if debounce is false. If it is, it makes debounce true and waits 1 second, then makes it false. Also, I added :GetService as improvements.

0
Don't forget to use debounce also on the server, so players can't exploit to shoot really fast Leamir 3138 — 4y

Answer this question