Would this be a good way of detecting if a player is inside of a part?

I’m trying to check if a player is inside of a part every 2 seconds, would this be a good “secure” way of doing it?

while wait(2) do
	local touchedParts = arena.Hitbox:GetTouchingParts()
	if not touchedParts:FindFirstChild("HumanoidRootPart") then
		InProgress.Value = false
	end
end```

kinda, but I think spatial queries would be more code optimized? (not sure though)

Edit: Right, as @BananDev below me says.

1 Like

I think the script you provided would give you an error, because GetTouchingParts() returns a table. You can check out WorldRoot | Roblox Creator Documentation, I think it might be a great choice in this case.

1 Like

Thank you, how would I use that? I’m very confused, would I replace WorldRoot with the hitbox?

You use it like this:

local hitbox = workspace.Hitbox -- your hitbox part
local humanoidRootPart = character.HumanoidRootPart -- the HumanoidRootPart

local params = OverlapParams.new()
params.FilterDescendantsInstances = {humanoidRootPart}
params.FilterType = Enum.RaycastFilterType.Whitelist

local inPart = workspace:GetPartsInPart(hitbox, params)

if #inPart >= 1 then
    -- Player is in the part
end
2 Likes

Thank you, for some reason it’s still not working, whenever I go into the hitbox it still gets set to false every 2 seconds.

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local hitbox = workspace.Map["1v1 Arena"].Hitbox
		local humanoidRootPart = character.HumanoidRootPart

		local params = OverlapParams.new()
		params.FilterDescendantsInstances = {humanoidRootPart}
		params.FilterType = Enum.RaycastFilterType.Whitelist

		local inPart = workspace:GetPartsInPart(hitbox, params)

		while wait(2) do
			if #inPart < 1 then
				InProgress.Value = false
			elseif #inPart >= 1 then
				InProgress.Value = true
			end
		end	
	end)
end)```

You gotta call the GetPartsInPart() in your loop. Also for the sake of performance, I recommend you breaking the loop once the character dies/despawns, something like this:

while wait(2) do
    if not character:IsDescendantOf(workspace) then break end
    -- rest of your code
end
1 Like
local players = game:GetService("Players")
local player = players.LocalPlayer or players.PlayerAdded:wait()
local character = player.Character or player.CharacterAdded:wait()

while task.wait(2) do
	for i, v in pairs(character:GetChildren()) do
		if v:IsA("Part") or v:IsA("MeshPart") then --get joints of character
			local touchedByJoint = v:GetTouchingParts() --get parts touched by any joint
			for _, val in pairs(touchedByJoint) do --traverse over those touched parts
				if val.Name == "" then --name of part you want to check
					--do some code
				end
			end
		end
	end
end

I believe this is the simplest solution and most efficient to the problem.