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

How do you make a pad that damages characters standing on it every second?

Asked by 3 years ago

I have a part with just a script attached to it. This is inside the script:

local trap = script.Parent

local RESET_SECONDS = 1
local isTouched = false  -- Declare debounce variable

local function damagePlayer(otherPart)
    local partParent = otherPart.Parent
    local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")

    if humanoid then
        if not isTouched then  -- Check that debounce variable is not true
            isTouched = true  -- Set variable to true
            humanoid.Health = humanoid.Health - 10
            print("OUCH!")
            wait(RESET_SECONDS)  -- Wait for reset time duration
            isTouched = false  -- Reset variable to false
        end
    end
end

trap.Touched:Connect(damagePlayer)

This code does damage every second to players standing on the pad, but it doesn't damage players that stand still on the pad. A player has to move for the Touched event to fire.

How do you make a script that can detect any player in contact with the pad and deal damage even if the player is not moving?

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

I solved the problem by using the function GetTouchingParts(). I did a similar thing with a gold giver script.

local GoldGiver = script.Parent

local Players = game:GetService("Players")

local function FindCharacterFromPart(part)
    local possibleCharacter = part:FindFirstAncestorOfClass("Model")
    if possibleCharacter and possibleCharacter:FindFirstChildOfClass("Humanoid") and (possibleCharacter:FindFirstChild("HumanoidRootPart") or possibleCharacter:FindFirstChild("Torso")) then
        return possibleCharacter --Since it is known that the model is a character, return the character
    else 
        return nil
    end
end


while wait(1) do 
    local touchingParts = GoldGiver:GetTouchingParts()
    local touchingCharacters = {}
    for i, part in ipairs(touchingParts) do
        if (FindCharacterFromPart(part) ~= nil) and not table.find(touchingCharacters,FindCharacterFromPart(part)) then
        table.insert(touchingCharacters, FindCharacterFromPart(part))
        end
    end
    for k, character in ipairs(touchingCharacters) do
        local player = Players:GetPlayerFromCharacter(character)
        local gold = player:WaitForChild("leaderstats"):WaitForChild("Gold")
        gold.Value = gold.Value + 1
    end 
end
Ad

Answer this question