Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

NPC only take away 5 health?

Asked by 7 years ago

I have made a script that will take away 5 health when touched

function onTouched(hit)
    local human = hit.Parent:findFirstChild("Humanoid")
    if (human ~= nil) then
        human.Health = human.Health - 5  
    end
end


script.Parent.Touched:connect(onTouched) 

how do i make it so when touching it will only take away 5 per every 2 seconds?

2 answers

Log in to vote
2
Answered by
Azarth 3141 Moderation Voter Community Moderator
7 years ago

To add to Nexiterate - if you want the script (wait of 2 seconds) to be separate for every player who touches the brick.


local touchers = {} local part = script.Parent local function damage(player) local hum = player.Character:findFirstChild("Humanoid") if hum then hum:TakeDamage(5) end touchers[player.Name] = tick() -- Update the last time they were damaged end part.Touched:connect(function(hit) if hit and hit.Parent then local player = game.Players:GetPlayerFromCharacter(hit.Parent) if player then local index = touchers[player.Name] if not index then -- if player isn't even in the table yet, then damage them. damage(player) else -- if the player is in the table if tick() - index >= 2 then -- If the last time they were damage was more than or equal to 2 seconds, then damage them. damage(player) end end end end end)
Ad
Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

You may achieve that using a debounce that the roblox wiki has some helpful and detailed info about what a debounce is and how to use it, you can check that out here

The code you could use is the following:

local debounce = false
function onTouched(hit)
    local human = hit.Parent:findFirstChild("Humanoid")
    if human and not debounce then
    debounce = true -- changing it to true so if the player touches it again before the two seconds have passed it would not run
        human.Health = human.Health - 5  
    wait(2) -- the function will only run if debounce is set to false, so here it waits two seconds then it reverts it back to being false
    debounce = false
    end
end

script.Parent.Touched:connect(onTouched) 

Hope it helped! If you have any questions please do not hesitate to let me know.

Answer this question