Hello! I’ve been learning region or GetPartsBoundsInBox; it’s useful. However, I am curious on how do I detect if a player left the region? thank you.
local RegionPart = workspace:WaitForChild('Part')
local params = OverlapParams.new()
params.FilterDescendantsInstances = {RegionPart}
params.FilterType = Enum.RaycastFilterType.Exclude
params.MaxParts = 5
while true do
task.wait()
local PartsInRegion = workspace:GetPartBoundsInBox(CFrame.new(RegionPart.CFrame.X, RegionPart.CFrame.Y, RegionPart.CFrame.Z), Vector3.new(RegionPart.Size.X, RegionPart.Size.Y, RegionPart.Size.Z), params)
local CharacterTable = {}
for i, part in pairs(PartsInRegion) do
if part.Parent:FindFirstChildOfClass("Humanoid") and not table.find(CharacterTable, part.Parent) then
table.insert(CharacterTable, part.Parent)
print(CharacterTable)
end
end
params:AddToFilter(CharacterTable)
end
You could check which players are in the region and see if they’re in the CharacterTable. If they aren’t in the region but are in the CharacterTable, they have left.
This should be pretty easy, just use your current script, but you could preferentially have two tables, the table of the players in the region previously, and create a new table of the current players, compare those two tables, if there’s any players in the table previously that aren’t there now, you know a player left. And you can call a function or do some work. Here’s an example:
local RegionPart = workspace:WaitForChild('Part')
local params = OverlapParams.new()
params.FilterDescendantsInstances = {RegionPart}
params.FilterType = Enum.RaycastFilterType.Exclude
params.MaxParts = 5
local currentCharacters = {}
while task.wait() do
local PartsInRegion = workspace:GetPartBoundsInBox(CFrame.new(RegionPart.CFrame.X, RegionPart.CFrame.Y, RegionPart.CFrame.Z), Vector3.new(RegionPart.Size.X, RegionPart.Size.Y, RegionPart.Size.Z), params)
local newCharacters = {}
for _, part in PartsInRegion do
if part.Parent:FindFirstChildOfClass("Humanoid") and not table.find(CharacterTable, part.Parent) then
table.insert(newCharacters, part.Parent)
end
end
for _, oldCharacter in currentCharacters do
if not table.find(newCharacters, oldCharacter) then
-- do some work here for the left character
end
end
currentCharacters = newCharacters
end