How can I make my punch script only do damage when punching?

  1. What do you want to achieve? a punch script

  2. What is the issue? the script does damage any time the right hand touches something, not just when the player uses the kieybind

  3. What solutions have you tried so far? I tried switching the debounces around thinking that was the problem but it didn’t work.

please note that I’m new to scripting and most of this is just me putting together pieces of code to make it work

here’s the code

local canPunch = true
local Keybind = "F"
local damage = 15

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.F then
		local anim = script.Parent.Parent.Humanoid:LoadAnimation(script.Animation)
		anim:Play()
		script.Parent.Parent.RightHand.Touched:connect(function(hit)
			if hit.Parent.Humanoid and canPunch == true then
				hit.Parent.Humanoid:TakeDamage(damage)
				canPunch = false
				wait(1)
				canPunch = true
			end
		end)
	end
end)
1 Like

Very simple. While the animation is still playing set a variable called CurrentlyPunching to true and after the animation is over set it to false. Only if CurrentlyPunching is true then damage.

local canPunch = true
local CurrentlyPunching = false
local Keybind = "F"
local damage = 15

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.F then
		local anim = script.Parent.Parent.Humanoid:LoadAnimation(script.Animation)
		anim:Play()
        CurrentlyPunching = true
        wait(1)
        CurrentlyPunching = false
	end
end)

script.Parent.Parent.RightHand.Touched:connect(function(hit)
    local model = hit:FindFirstAncestorOfClass("Model")
	if model and model:FindFirstChild("Humanoid") and canPunch and CurrentlyPunching then
		model:FindFirstChild("Humanoid"):TakeDamage(damage)
	    canPunch = false
		wait(1)
		canPunch = true
	end
end)

If this works for you, please set this post as the solution so others can easily find it if they have the same problem. Thank you.

4 Likes

That worked perfectly! Thank you so much