How to constantly check if a player is touching a part?

I have a part. I want a sound to be playing if any player is touching the part, but if nobody is touching the part I want the sound to stop playing. I used the Touch and TouchEnded events but those events worked very poorly so I need a new method.

3 Likes

You can use :GetPartsInPart() which is precise and returns a table with every part touching it.

More info: Introducing OverlapParams - New Spatial Query API

7 Likes

I had the same issue while making my game. I never really found a great way using “Touch” script but I used two parts instead, one enables and the other disables. Or you can detect if the player is close to the part and when they aren’t close to it then it stops working.
Or do what ever the guy above me said to do because I have no idea what that is.

Is it called :GetTouchingParts() now?

No, GetPartsInPart is the newer one that allows for more customization.

Are you sure because devhub says it can only be used on a “WorldRoot” and I have no idea what that is?

Can you give a code example?

1 Like

Basically, WorldRoot is Workspace (this is a bit simplified)

local touchingParts = workspace:GetPartsInPart(partHere)
19 Likes

Hey thanks it worked! I figured out how to make the sound start, but I’m still working on getting the part to stop.

local sound = game.Workspace.Sounds.Alarm
local players = game:GetService("Players")
sound.Playing = false

while wait() do
	local touching = game.Workspace:GetPartsInPart(script.Parent)
	for i, v in pairs(touching) do
		if v.Parent:FindFirstChild("Humanoid") ~= nil then
			local player = players:GetPlayerFromCharacter(v.Parent)
			if player.Team.Name ~= "Night Guard" then
				sound.Playing = true
			end
		end
	end
end
4 Likes

Okay I figured it out. Let me know if I can improve this.

local sound = game.Workspace.Sounds.Alarm
local players = game:GetService("Players")
sound.Playing = false

while wait() do
	local touching = game.Workspace:GetPartsInPart(script.Parent)
	local playerInPart = false
	for i, v in pairs(touching) do
		if v.Parent:FindFirstChild("Humanoid") ~= nil then
			playerInPart = true
		end
	end
	print(playerInPart)
end
1 Like

This should be replaced with task.wait().

1 Like

How come?‎‎ ``

It’s more accurate, and doesn’t throttle.
More info:

2 Likes