Best way for AABB region detection?

I want the server to check if any player is inside a certain region using simple if statements.
My question is, is there a better way to do that? I’ve heard using .Touched is unreliable, and I’m sure using workspace:GetPartBoundsInBox() is no more efficient than this as it most likely uses more complicated geometry.

Yes, I’m very picky when it comes to performance.

-- Check if position is inside kill region
local function IsPositionInRegion(position: Vector3)
	return position.X > kill_region_position.X - kill_region_size.X and position.X < kill_region_position.X + kill_region_size.X and position.Z > kill_region_position.Z - kill_region_size.Z and position.Z < kill_region_position.Z + kill_region_size.Z and position.Y < kill_region_position.Y + kill_region_size.Y
end

-- Detect character added
local function OnCharacterAdded(character: Model)
	local humanoid: Humanoid = character.Humanoid
	local root_part: BasePart = humanoid.RootPart

	-- If humanoid is alive, exists somewhere, and is not in kill region, then wait
	while humanoid.Health > 0 and humanoid.Parent and not IsPositionInRegion(root_part.Position) do
		task.wait()
	end

	-- murder
	humanoid.Health = 0
end

Thanks for reading : )

this is probably the fastest way to do it

you can also use player:DistanceFromCharacter(pos: Vector3) which is probably even faster but only works for spherical regions

If you want to detect other parts like the arm touching instead of only the center of the humanoid root part you can put the characters inside of a folder and then use a spatial query like workspace:GetPartsInPart() with an overlapparameter that only includes that folder for fast performance

2 Likes