How do I get a player from a zone?

There are already threads with this kind of titles, but they didn’t help me, I want to know when a player is on a zone and do a function, or when they leave that zone and stop that function. But I don’t know how to do it, I want to make this simple :slight_smile:, thanks for reading.

1 Like

Define ‘zone’?

30 characters

Inside a region, in a block for example.

Anyways, if what you mean by functions is a connection (part.Touched:Connect(function()end)), then you can say this:

connection = part.Touched:Connect(function(hit)
  print("Disconnecting…")
  connection:Disconnect()
  print("Disconnected!")
end)
1 Like

ooh nice

To get a region from a block, use the formula pos - size/2 for the min, and pos + size/2 for the max. To get corner

local function from_part(part)
    local pos, half_size = part.Position, part.Size/2
    return Region3.new(pos - half_size, pos + half_size)
end

There exists a method, Workspace:FindPartsInRegion3(Region3 reg, Instance ignore = nil, int max_parts = 20).

It returns an array of all the parts in the region. The nice function I gave you lets you create from a part so the region the part covers is now covered by the region3

If you are using an invisible/non-collide brick to define your region, here is a function that can determine if a given Vector3 position is inside of it:

function isInsideBrick(position, brick)
	local v3 = brick.CFrame:PointToObjectSpace(position)
	return (math.abs(v3.X) <= brick.Size.X / 2)
		and (math.abs(v3.Y) <= brick.Size.Y / 2)
		and (math.abs(v3.Z) <= brick.Size.Z / 2)
end

This should work regardless of the hitbox’s rotation.

44 Likes

@myaltaccountsthis touched is not too efficient.

@Blokav @incapaxx

But how do I get the player? That will get the area, but I want to know when the player gets on that area.

As I said, :FindPartsInRegion3 returns an array of parts in the region.

for _, part in ipairs(parts_in_region3) do
    local client = Players:GetPlayerFromCharacter(part.Parent)
end

Pseudocode

Also one thing I forgot to point out, which @Blokav reminded me of, is you can’t rotate a region3, so my method may not be the best if your part will be rotating

Iterate through all players and select the ones whose characters are in the region:

function getPlayersInsideZone(zone)
	local list = {}
	for _, player in ipairs(game.Players:GetPlayers()) do
		if (player.Character) then
			local torso = player.Character:FindFirstChild("HumanoidRootPart")
			if (torso and isInsideBrick(torso.Position, zone)) then
				table.insert(list, player)
			end
		end
	end
	return list
end
2 Likes

You can do BasePart:GetTouchingParts(), it returns a table of the touching parts.