Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make a part do continuous damage when you stand on it?

I am trying to make a part where you stand on the part and whilst standing on it you will take damage the remainder of the time you are standing on it. Once the player comes off the part the damage is stopped. Here's the code;

-- When player touches part and it is true, health decreases by 10

local decrease = script.Parent
local HEALTH = 100

local function onTouch(plr)	
	
	print("Ouch")
	local player = plr.Parent
	local character = player:FindFirstChildWhichIsA("Humanoid")
	if character then
	character.Health = HEALTH - 10
			
		end
	end
decrease.Touched:Connect(onTouch)

This would help me figure out if someone could answer!

1 answer

✓ Accepted answer

So this exposes the weakness of the Touched function, you can use the function GetPartsInPart instead which returns an array of parts touching the block, and loop through every part touching the block.

local playersTouching = {}--we use an array to insert the players touching the block
while true do
	wait(1)
	local touchingParts = game.Workspace:GetPartsInPart(script.Parent)
	table.clear(playersTouching)--clear the array first because the player might not be touching the block anymore
	for i,v in pairs(touchingParts) do
		if v.Parent:FindFirstChild("Humanoid") and not table.find(playersTouching,v.Parent) then--check if the player is inside the playersTouching table already, because there will be 2 leg part of a single player inside the touchingParts array, this prevents a player being inserted twice into the playersTouching table
			table.insert(playersTouching,v.Parent)
		end
	end
	for i,v in pairs(playersTouching) do--loops through all the players touching the block to decrease their health
		local humanoid = v:FindFirstChild("Humanoid")
		
		humanoid.Health -=2
	end
	
end

Its been a long while since i coded in roblox so this might not be the most efficient way but this will work for your given case.

2 comments

0

I still haven't learned Arrays nor Tables so this very much confuses me including the i,v pairs part especially but I am using roblox devhub so slowly figuring out but thank you!

0

i,v pairs is used to loop through the elements of an array, the i represents the index of the current element, and v represents the value of the element, you can get a better understanding when you print i and v and watch the output. arrays are just a collection of instances, the instances in this case being the players and player parts. You can read more about this online, happy learning!

This discussion is preserved as it was. New answers, comments, and votes are closed.