Search code examples
luagarrys-mod

Garry's Mod Lua: How to make delay/cooldown?


I have IN_USE set up as my primary attack instead of SWEP:PrimaryAttack on purpose. But doing that, it has made it where I can spam attack and So i'm looking for a delay/cooldown to it. I've looked around at CurTime and things; however, I already have an IF then Else statement and unsure how to use CurTime coding into it.

function SWEP:Think()
    if self.Owner:KeyDown(IN_USE) && self.Owner:IsPlayer() then
        local Angles = self.Owner:GetAngles()

        self:SendAnim()   
        self:SetWeaponHoldType( "melee" )
        timer.Simple(0.1, function() 
            if not IsValid(self) or not self.Owner:Alive() then return end self.Weapon:EmitSound( "weapons/iceaxe/iceaxe_swing1.wav" ) self.Weapon:PrimarySlash() self.Owner:SetAnimation( PLAYER_ATTACK1 ) end )
        timer.Simple(0.35, function() 
            if not IsValid(self) or not self.Owner:Alive() then return end self.Weapon:EmitSound( "weapons/iceaxe/iceaxe_swing1.wav" ) self.Weapon:PrimarySlash() end)
        timer.Simple(0.5, function() if not IsValid(self) or not self.Owner:Alive() then return end self:SetWeaponHoldType( "knife" ) end)
    end

Solution

  • function SWEP:Initialize()
        self.NextUseTime = CurTime()
        self.UseDelay = 1.5
    end
    
    function SWEP:Think()
        if self.Owner:KeyDown(IN_USE) && self.Owner:IsPlayer() && ( self.NextUseTime - CurTime() <= 0 ) then
            local Angles = self.Owner:GetAngles()
    
            self:SendAnim()   
            self:SetWeaponHoldType( "melee" )
            timer.Simple(0.1, function() 
                if not IsValid(self) or not self.Owner:Alive() then return end self.Weapon:EmitSound( "weapons/iceaxe/iceaxe_swing1.wav" ) self.Weapon:PrimarySlash() self.Owner:SetAnimation( PLAYER_ATTACK1 ) end )
            timer.Simple(0.35, function() 
                if not IsValid(self) or not self.Owner:Alive() then return end self.Weapon:EmitSound( "weapons/iceaxe/iceaxe_swing1.wav" ) self.Weapon:PrimarySlash() end)
            timer.Simple(0.5, function() if not IsValid(self) or not self.Owner:Alive() then return end self:SetWeaponHoldType( "knife" ) end)
    
            self.NextUseTime = CurTime() + self.UseDelay
        end
    

    In case you already have a SWEP:Initialize function, just copy the contents across and add it to your existing function.