Best way run code while a part is being touched in Roblox Studio

  1. I want to make a pressure plate that player or a part touch it or get close to it it run some code while it touching but I cant really a good way to detect the touching

  2. Issue i cant FIND ANY

  3. I have tried touch event I don’t know when player walk on it it just keep connecting and stop connecting one i found is and other work but it still use like check every frame so it still lag

local Open = false
game:GetService("RunService").Heartbeat:Connect(function()

	for i,v in pairs(ThingCanPress) do
		local distance = (ThingCanPress.Position-v.Position).Magnitude
		if distance < 5.2 then
			Open = true
		else
			Open = false
		end
	end
end

which work BUT it make my game lag ALOT(idk if my pc bad or not)
so I wonder is there any optimal way to do it
Thank you

1 Like

Theres no need to use runservice use touched events and add a debounce if needed

well pressure plate also have to detect you know stop touching but touched event fire a bunch when player walk on it

You do know that BasePart.TouchEnded exists, right?

You could extend a hitbox upwards and check for specifically the root part instead of any limb using touched connections.

3 Likes

To detect when a player Starts & Stops touching a part, use the Touched events:

local TouchPart = script.Parent -- Where your part is

TouchPart.Touched:Connect(function(Hit)
     -- Your Logic Here
end)

TouchPart.TouchEnded:Connect(function(Hit)
     -- Your Logic Here
end)

Script that also checks if the hit is a player:

local TouchPart = script.Parent -- Where your part is

TouchPart.Touched:Connect(function(Hit)
    if not Hit.Parent:FindFirstChild("Humanoid") then return end
    -- Your Logic Here
end)

TouchPart.TouchEnded:Connect(function(Hit)
    if not Hit.Parent:FindFirstChild("Humanoid") then return end
    -- Your Logic Here
end)

Make it only do the action once when the player touches the button, and wait until they get off before allowing another input:

local TouchPart = script.Parent -- Where your part is
local Debounce = false

TouchPart.Touched:Connect(function(Hit)
     if not Hit.Parent:FindFirstChild("Humanoid") or Debounce == true then return end
     Debounce = true
     -- Your Logic Here
end)

TouchPart.TouchEnded:Connect(function(Hit)
     if not Hit.Parent:FindFirstChild("Humanoid") then return end
     Debounce = false
     -- Your Logic Here
end)

oh yeah… I could just have extend the part upward and it works… Thank you guys

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.