Search code examples
luarobloxluau

Part doesn't gives damage with Touched Event


I made a code for my game, it's a type of punch, with a hitbox made with a common Part. I proggrammed to the part give some damage according with the player strenght. It didn't work, no errors in output. Code here:

local rep = game:GetService("ReplicatedStorage")
local debounceDMG = true

rep.Combate.Soco.OnServerEvent:Connect(function(plr)
    local math = math.random(1,2)
    local char = plr.Character or plr.CharacterAdded:Wait()
    local Humanoid = char.Humanoid
    local lanim = char.Humanoid:LoadAnimation(script.Left)
    local lanim1 = char.Humanoid:LoadAnimation(script.Animation)
    local hitbox = Instance.new("Part")
    hitbox.Parent = workspace
    hitbox.Transparency = 1
    hitbox.Anchored = true
    hitbox.CanCollide = false
    hitbox.Size = Vector3.new(2.5,2.5,2.5)
    game:GetService("RunService").Heartbeat:Connect(function()
        if math == 2 then
            hitbox.Position = char.LeftHand.Position
        elseif math == 1 then
            hitbox.Position = char.RightHand.Position
        end
    end)
    if math == 2 then
        lanim:Play()
    elseif math == 1 then
        lanim1:Play()
    end
    hitbox.Touched:Connect(function(hit)
        local h = hit.Parent:FindFirstChild("Humanoid")
        if h then
            if h ~= Humanoid and debounceDMG then
                debounceDMG = false
                h.Health -= plr.Data.Forca.Value + 5
                task.wait(.5)
                debounceDMG = true
            end
        end
    end)
    task.wait(.3)
    hitbox:Destroy()
end)

Solution

  • You use "if h~=Humanoid" will always look for Non Humanoid, your code will never reach the Health deduction. Try to code below if working

      hitbox.Touched:Connect(function(hit)
            local h = hit.Parent:FindFirstChild("Humanoid")
            if h ~= nil and debounceDMG then
                debounceDMG = false
                h.Health -= plr.Data.Forca.Value + 5
                task.wait(.5)
                debounceDMG = true
            end
        end)