I am trying to create a part that damages players for 20 health every 2 seconds, but Part.Touched is unreliable and if they stay still it can’t detect them. It would be useful if it could detect them if they were in a range of 20 studs of something.
This is the best I got so far:
local playerService = game:GetService("Players")
while wait(1) do
for _,v in pairs(workspace:GetPartBoundsInBox(script.Parent.CFrame,script.Parent.Size)) do
if v.Parent:FindFirstChild("Humanoid") then
local humanoid = v.Parent:FindFirstChild("Humanoid")
if playerService:GetPlayerFromCharacter(humanoid.Parent).Team == game.Teams.Red then
v.Parent.Humanoid.Health = v.Parent.Humanoid.Health - 20
v.Parent.Humanoid:TakeDamage(5)
end
end
end
end
@TheCraftNCreator is indeed right.
But one Problem I have seen, which you will report, is that you get more than 5 damage. This is because of the multiple parts you have in the character that gets detected from the Character.
You may use a Table local x = {} and get all the players that already have been damaged within the time. table.insert(x, player) to insert into the table, as x[player] = true is not needed
@TheCraftNCreator It seems to work! Also @nayro007 I did notice that humanoid:TakeDamage() did damage the player more, but it does not happen when setting the humanoid health directly. I assume this is how I would run the script:
local playerService = game:GetService("Players")
while wait(1) do
for _,v in pairs(workspace:GetPartBoundsInBox(script.Parent.CFrame,script.Parent.Size)) do
if v.Parent:FindFirstChild("Humanoid") then
local humanoidRoot = v.Parent:FindFirstChild("HumanoidRootPart")
local humanoid = v.Parent:FindFirstChild("Humanoid")
if (humanoidRoot.Position - script.Parent.Position).Magnitude <= 20 then
print("Damaged")
humanoid.Health = humanoid.Health - 20
end
end
end
end