Which way of using touched event is better?

Hey, i have question, i didn’t used touched event for a long time and i need it, if you ask i will have static objects that will not move at all and damage players such as spikes and barbed wire

Question is how should i run this event?
My current idea is to use:

  • Check touched event on every trap-object’s hitbox
  • Check touched event on player’s hitbox and then determine if part touched should damage player

In my experience using Humanoid.Touched is easier. Not sure about peformance though.

1 Like

u can edit this to ur needs ( this is a damage brick )

local dmg = 5
local debounce = false

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and debounce == false then
		debounce = true
		hit.Parent.Humanoid:TakeDamage(dmg)
        task.wait(0.01)
        debounce = false
	end
end)

Just a tip try not to parent server-scripts to parts in the workspace for organization purposes, and this debounce boolean seems to be server-sided meaning that it can have some problems for other players.

For example, what if 2 players step on the brick at the same time? A potential bug.

I recommend using CollectionService

I asked about which way i can use it because i want performance, i can detect if player touched something or if something touched player

ye thats true also collectionservice for adding and removing tags to check if they can take dmg is a good idea

um touched, is uh good for performance?

but it can be bad if used in specific ways, i don’t know if hitbox attached to player will be better because it will touch literally everything, but listening for 100+ events isn’t good idea too

Oh, then you shouldn’t used touched because it’s detection rate isn’t the best. Use a spatial query like getpartsinbounds instead.

You can either use it in a while loop or if its a fighting game when a player clicks the tool you can set up an event and then use getpartsinbounds that way.

as i said i want to use it for static objects detection, spatial querry is laggy if i need to check it every frame or so

Yeah you don’t need to check it every frame though you can use an event instead, i’m not sure what type of game you are making but if it’s a fighting game set up an event where as soon as the player clicks the attack tool use getpartsboundsinbox.

Also even if you did do it every frame it’s not that intensive on performance actually. Unless it’s a giant area you are checking.

i want to damage player when he touches barbed wire or spikes

EDIT: I forget to mention there will be hundreds of those traps

2 Likes