So what I mean is that when my NPC touches a player, it will deal damage. But what my script does is make the NPC deal 5 damage repeatedly since a player is constantly touching the hitbox of the NPC. How would you fix this to make the NPC deal 5 damage every second?
npc = script.Parent local human = npc:WaitForChild("NPC") --different humanoid name so npcs dont kill each other local hitbox = npc:WaitForChild("HitBox") --welded a hitbox hitbox.Touched:connect(function(hit) local hum = hit.Parent:FindFirstChild("Humanoid") if hum then local swing1 = human:LoadAnimation(script.Swing1) local swing2 = human:LoadAnimation(script.Swing2) local choose = math.random(1,2) if choose == 1 then swing1:Play() elseif choose == 2 then swing2:Play() end hum:TakeDamage(5) end end end)
This should work:
npc = script.Parent local human = npc:WaitForChild("NPC") --different humanoid name so npcs dont kill each other local hitbox = npc:WaitForChild("HitBox") --welded a hitbox local can = true hitbox.Touched:connect(function(hit) local hum = hit.Parent:FindFirstChild("Humanoid") if can then if hum then can = false local swing1 = human:LoadAnimation(script.Swing1) local swing2 = human:LoadAnimation(script.Swing2) local choose = math.random(1,2) if choose == 1 then swing1:Play() elseif choose == 2 then swing2:Play() end hum:TakeDamage(5) wait(1) can = true end end end)
http://wiki.roblox.com/index.php?title=Debounce
Can only damage once per second.
local tabl = {} local function damage_player(player, hum) hum:TakeDamage(5) tabl[player.Name] = tick() -- Reset the time we last touched the npc end script.Parent.Touched:Connect(function(hit) local player = game.Players:GetPlayerFromCharacter(hit.Parent) if player and player.Character then local hum = player.Character:findFirstChild("Humanoid") if hum and hum.Health > 0 then local indexed = tabl[player.Name] if indexed then -- Player has touched the nps before. if tick() - indexed >= 1 then -- if the last time we touched is more than 1s ago. damage_player(player, hum) end else --Player isn't in the table yet, so damage anyways and index them. damage_player(player, hum) end end end end)
Damages continuously after walking away.
local tabl = {} local function damage_player(player, hum) spawn(function() while true do if hum.Health <= 0 then break end hum.Health = hum.Health - 5 wait(1) end print(player.Name.. " is dead to me.") end) end script.Parent.Touched:Connect(function(hit) local player = game.Players:GetPlayerFromCharacter(hit.Parent) if player and player.Character then local hum = player.Character:findFirstChild("Humanoid") if hum and hum.Health > 0 then local indexed = tabl[player.Name] if not indexed then tabl[player.Name] = true damage_player(player, hum) end end end end)