Skip to content

Instantly share code, notes, and snippets.

@mvyasu
Last active October 8, 2026 15:56
Show Gist options
  • Select an option

  • Save mvyasu/fee3c2a0ff2ae4bde39328efdbc55b4c to your computer and use it in GitHub Desktop.

Select an option

Save mvyasu/fee3c2a0ff2ae4bde39328efdbc55b4c to your computer and use it in GitHub Desktop.
Useful for hooking up code to tagged parts that are nearby
--by @mvyasu
--Oct 28th 2022
export type TrackerConfig = {
SearchTag: string,
SearchTagCount: NumberRange,
SearchTagCountClamped: boolean?,
SearchCollisionGroup: string?,
SearchRate: number?,
SearchPosition: ((() -> Vector3) | Vector3)?,
TrackTag: string,
TrackRadius: number,
UntrackRadius: number,
TrackDelayOptimization: boolean?,
}
local CLEANUP_SYMBOL = newproxy()
local RUNNING_SYMBOL = newproxy()
local function defaultSearchPosition(): Vector3
local camera = workspace.CurrentCamera
local character = game.Players.LocalPlayer.Character
return if (character and camera.CameraType == Enum.CameraType.Custom) then character:GetPivot().Position else camera.CFrame.Position
end
local Tracker = {}
Tracker.__index = Tracker
function Tracker.new(config: TrackerConfig)
local self = setmetatable({}, Tracker)
self[CLEANUP_SYMBOL] = {}
self[RUNNING_SYMBOL] = false
self.SearchTag = config.SearchTag
self.SearchTagCount = config.SearchTagCount
self.SearchTagCountClamped = config.SearchTagCountClamped
self.SearchRate = config.SearchRate or 1
self.SearchPosition = config.SearchPosition or defaultSearchPosition
self.SearchCollisionGroup = config.SearchCollisionGroup or "Default"
self.TrackTag = config.TrackTag
self.TrackRadius = config.TrackRadius
self.UntrackRadius = config.UntrackRadius
self.TrackDelayOptimization = config.TrackDelayOptimization
self:Start()
return self
end
function Tracker:Start()
if self[RUNNING_SYMBOL] then
return
end
self[RUNNING_SYMBOL] = true
local function cleanupAdd(object: any)
table.insert(self[CLEANUP_SYMBOL], object)
end
local queryParamsNeedToBeUpdated = true
local allowedNearbyParts = self.SearchTagCount.Min do
local function calculateAllowedNearbyParts()
local currentGraphicsLevel = UserSettings().GameSettings.SavedQualityLevel.Value
local min, max = self.SearchTagCount.Min, self.SearchTagCount.Max
local unclampedPartCount = math.floor(math.map(currentGraphicsLevel, 1, 10, min, max))
allowedNearbyParts = if self.SearchTagCountClamped then math.clamp(unclampedPartCount, min, max) else unclampedPartCount
end
calculateAllowedNearbyParts()
cleanupAdd(UserSettings().GameSettings:GetPropertyChangedSignal("SavedQualityLevel"):Connect(calculateAllowedNearbyParts))
end
local overlapParams = OverlapParams.new()
overlapParams.CollisionGroup = self.SearchCollisionGroup
local CollectionService = game:GetService("CollectionService")
-- Maps each tagged instance (Part or Model) to the BasePart used for proximity.
-- For plain Parts: taggedInstance == proxyPart
-- For Models: proxyPart == Model.PrimaryPart (or nil when unset)
-- Maps proxyPart → taggedInstance so we know what to tag/untag.
local proxyToInstance: {[BasePart]: Instance} = {}
local currentProxyParts: {BasePart} = {}
local primaryPartConnections: {[Model]: RBXScriptConnection} = {}
local willUpdate = false
local function rebuildProxyList()
if willUpdate then
return
end
willUpdate = true
task.defer(function()
willUpdate = false
table.clear(currentProxyParts)
for proxy, _ in proxyToInstance do
table.insert(currentProxyParts, proxy)
end
queryParamsNeedToBeUpdated = true
end)
end
-- Register or re-register a tagged instance, resolving its proxy part.
local function registerInstance(instance: Instance)
if instance:IsA("Model") then
-- Clean up any old proxy that was registered for this Model
for proxy, owner in proxyToInstance do
if owner == instance then
proxyToInstance[proxy] = nil
break
end
end
local primary = instance.PrimaryPart
if primary then
proxyToInstance[primary] = instance
end
-- (If PrimaryPart is nil we simply don't add a proxy yet;
-- the PrimaryPart-change listener below will catch it.)
-- Watch for PrimaryPart changes on this Model
if not primaryPartConnections[instance] then
local conn = instance:GetPropertyChangedSignal("PrimaryPart"):Connect(function()
-- Remove the old proxy entry for this model
for proxy, owner in proxyToInstance do
if owner == instance then
proxyToInstance[proxy] = nil
break
end
end
-- Add the new one if it exists
local newPrimary = instance.PrimaryPart
if newPrimary then
proxyToInstance[newPrimary] = instance
end
rebuildProxyList()
end)
primaryPartConnections[instance] = conn
cleanupAdd(conn)
end
else
-- Plain BasePart: the instance is its own proxy
proxyToInstance[instance :: BasePart] = instance
end
rebuildProxyList()
end
local previousNearbyInstances: {Instance} = {}
local function unregisterInstance(instance: Instance)
if instance:IsA("Model") then
local conn = primaryPartConnections[instance]
if conn then
conn:Disconnect()
primaryPartConnections[instance] = nil
end
for proxy, owner in proxyToInstance do
if owner == instance then
proxyToInstance[proxy] = nil
break
end
end
else
proxyToInstance[instance :: BasePart] = nil
end
-- Immediately remove the TrackTag rather than waiting for the next loop tick
if table.find(previousNearbyInstances, instance) then
instance:RemoveTag(self.TrackTag)
end
rebuildProxyList()
end
-- Seed with whatever is already tagged
for _, inst in CollectionService:GetTagged(self.SearchTag) do
registerInstance(inst)
end
cleanupAdd(CollectionService:GetInstanceAddedSignal(self.SearchTag):Connect(registerInstance))
cleanupAdd(CollectionService:GetInstanceRemovedSignal(self.SearchTag):Connect(unregisterInstance))
local TRACK_DELAY = if self.TrackDelayOptimization then 0 else self.SearchRate/2
cleanupAdd(task.defer(function()
while true do
if queryParamsNeedToBeUpdated then
overlapParams.IncludeInstances = currentProxyParts
queryParamsNeedToBeUpdated = false
end
local searchPosition = self.SearchPosition
local queryPosition = if typeof(searchPosition)=="function" then searchPosition() else searchPosition
local hitProxyParts = workspace:GetPartBoundsInRadius(queryPosition, self.UntrackRadius, overlapParams)
table.sort(hitProxyParts, function(a, b)
return (queryPosition - a.Position).Magnitude < (queryPosition - b.Position).Magnitude
end)
-- Resolve proxy parts → tagged instances (deduplicated)
local seenInstances: {[Instance]: true} = {}
local currentNearbyInstances: {Instance} = {}
for _, proxy in hitProxyParts do
local inst = proxyToInstance[proxy]
if inst and not seenInstances[inst] then
seenInstances[inst] = true
table.insert(currentNearbyInstances, inst)
end
end
-- Enforce count limit
for i = #currentNearbyInstances, 1, -1 do
if i > allowedNearbyParts then
table.remove(currentNearbyInstances, i)
end
end
-- Only include instances within TrackRadius unless
-- they were already in the previous batch (hysteresis).
for i = #currentNearbyInstances, 1, -1 do
local inst = currentNearbyInstances[i]
-- Find the proxy position for distance check
local proxy: BasePart?
for p, owner in proxyToInstance do
if owner == inst then proxy = p; break end
end
local proxyPos = if proxy then proxy.Position else queryPosition
local wasInPreviousBatch = table.find(previousNearbyInstances, inst) ~= nil
if not wasInPreviousBatch and (proxyPos - queryPosition).Magnitude > self.TrackRadius then
table.remove(currentNearbyInstances, i)
end
end
-- Untag instances that left the set
for _, prevInst in previousNearbyInstances do
if not table.find(currentNearbyInstances, prevInst) then
prevInst:RemoveTag(self.TrackTag)
end
end
-- Tag instances that entered the set (with optional delay spread)
local totalInstances = #currentNearbyInstances
local delayPerPart = if totalInstances ~= totalInstances then 0 else TRACK_DELAY / math.max(totalInstances, 1)
local needsDelay = delayPerPart ~= 0
for _, inst in currentNearbyInstances do
inst:AddTag(self.TrackTag)
if needsDelay then
task.wait(delayPerPart)
end
end
previousNearbyInstances = currentNearbyInstances
task.wait(self.SearchRate - (if needsDelay then TRACK_DELAY else 0))
end
end))
end
function Tracker:Stop()
if not self[RUNNING_SYMBOL] then
return
end
self[RUNNING_SYMBOL] = false
local function cleanupObject(object: any)
local t = typeof(object)
if t == "function" then
object()
elseif t == "RBXScriptConnection" then
object:Disconnect()
elseif t == "table" or t == "Instance" then
if object.Destroy then
object:Destroy()
else
for _, child in pairs(object) do
cleanupObject(child)
end
table.clear(object)
end
elseif t == "thread" then
coroutine.close(object)
end
end
cleanupObject(self[CLEANUP_SYMBOL])
local CollectionService = game:GetService("CollectionService")
for _, part in CollectionService:GetTagged(self.TrackTag) do
part:RemoveTag(self.TrackTag)
end
end
Tracker.Destroy = Tracker.Stop
return Tracker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment