Add a debounce to action

I’m trying to make a slap script where you press a key to slap. I don’t know where to add the debounce so you can’t just repeatedly spam click “f” and spam the animation.

Script

CanDoDmg = true
Key = "f" 
Damage = 25

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.KeyDown:Connect(function(key)
	if key == Key then
		local anim = script.Parent.Humanoid:LoadAnimation(script.Slap)
		anim:Play()
		script.Parent["Right Arm"].Touched:connect(function(hit)
			if hit.Parent.Humanoid and CanDoDmg == true then
				hit.Parent.Humanoid:TakeDamage(Damage)
				CanDoDmg = false
				wait(1)
				CanDoDmg = true
			end
		end)
	end
end)

swap around the boolean

it should be CanDoDmg = true then wait(1) then CanDoDmg = false

If I do that, if the part, in this case the Right Arm, touches the NPC even without pressing they key then the humanoid will still take damage.

Wait never mind, it does it either way

if key == Key and CanDoDmg ~= false then

CanDoDmg = true
Key = "f" 
Damage = 25

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.KeyDown:Connect(function(key)
	if key == Key then
		local slapAnim = script:WaitForChild("Slap")
		local anim = script.Parent.Humanoid:LoadAnimation(slapAnim)
		anim:Play()
		script.Parent["Right Arm"].Touched:Connect(function(hit)
			if not CanDoDmg then
				return
			end
			if hit.Parent.Humanoid then
				hit.Parent.Humanoid:TakeDamage(Damage)
				CanDoDmg = false
				wait(1)
				CanDoDmg = true
			end
		end)
	end
end)

Slightly changed some of the logic, also the 2nd “Connect” function lacked a capital “C”.

CanDoDmg = true
Key = "f" 
Damage = 25
local LastAttackTime = os.time()
local AttackDelay = 5 -- How long you want to wait before you can attack again (seconds)

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.KeyDown:Connect(function(key)
	if key == Key then
		local anim = script.Parent.Humanoid:LoadAnimation(script.Slap)
		anim:Play()
		script.Parent["Right Arm"].Touched:connect(function(hit)
			if hit.Parent.Humanoid and os.time() - LastAttackTime >= AttackDelay then
				hit.Parent.Humanoid:TakeDamage(Damage)
			end
		end)
	end
end)
1 Like

I tried it and it started doing thousands of damage.

Would using a remote event help? I’m still able to spam click f and after the animation plays, even though im not pressing anything, the right arm still does damage when touched.

I don’t recommend you use Remote Events because it’s Exploitable, unless you use them at a place Local Editors can’t see
Since most Exploits are Local it’s going to be harder to find the Remote Event