I made aggressive Npc that deals damage to nearest player in distance, but damaging debounce doesnt work properly
NPC deal damage TWICE before his debounce set to true, I think thats cause of heartbeat function but i dont know how to fix it
Script:
local char = script.Parent
local hum = char:FindFirstChildOfClass("Humanoid")
local animator = hum:FindFirstChildOfClass("Animator")
local hrp = char.PrimaryPart
local detectPart = hrp
local maxDistance = 30
local idleAnim = animator:LoadAnimation(script.idle)
local walkAnim = animator:LoadAnimation(script.walk)
idleAnim:Play()
local function hasProperty(object, prop)
local t = object[prop]
end
for i,v in pairs(script.Parent:GetDescendants()) do
local success = pcall(function() hasProperty(v, "CollisionGroup") end)
if success then
v.CollisionGroup = "NPC"
end
if v:IsA("Part") or v:IsA("BasePart") or v:IsA("MeshPart") then
v:SetNetworkOwner(nil)
end
end
local debounce = false
game:GetService("RunService").Heartbeat:Connect(function()
local nearestPlayer, nearestDistance, distance
for _, player in pairs(game.Players:GetPlayers()) do
local character = player.Character
distance = player:DistanceFromCharacter(detectPart.Position)
if not character or
distance > maxDistance or
(nearestDistance and distance >= nearestDistance)
then
continue
end
nearestDistance = distance
nearestPlayer = player
end
if nearestPlayer ~= nil then
hum:MoveTo(nearestPlayer.Character.PrimaryPart.Position)
if idleAnim.IsPlaying then
idleAnim:Stop()
walkAnim:Play()
hum.WalkSpeed = 10
end
if distance < 2 and debounce == false then
spawn(function()
debounce = true <--------------
print("5 taken")
nearestPlayer.Character.Humanoid:TakeDamage(5)
task.wait(1)
debounce = false
end)
end
else
if walkAnim.IsPlaying then
walkAnim:Stop()
idleAnim:Play()
hum:MoveTo(hrp.Position)
end
end
end)