Comparing a distances

  • The Scenario
    have collectionserver:gettagged(“neatparts”)
    all that has a the tag “neatpart” will be inside an array

  • What i want to do
    compare the distances of the tagged parts in that array to the part “coolpart” and return the closest one

how would i achieve this efficiently since there can be hundreds of parts with the tag “neatpart”?

1 Like

I just used the search tool with the phrase ‘get closest part’ and got this post. There may be others as well.
Help about getting the closest part from a specific part

2 Likes

Just search through every part. You seem to be worried about optimization here, but you said there can be hundreds. That is pretty trivial for modern computers to handle so I wouldn’t worry to much. Just build the simplest possible form and only worry about performance if it becomes an issue.

If it ever does become an issue you could do 3 things, spread out the calculations to multiple clients. Spread it out across time (like do a bit every heartbeat instead of the whole list at once). Or finally using some acceleration structures like bvh or dividing your zone into squares or something. These all come with more complexity (except maybe that time one) so I would advise against doing these unless you need to because you probably won’t need it and they will just waste development time

2 Likes

This is what I would do for finding the closest distance.

local currentDist = 99999 --Set as a maximum distance
local currentTarget

local targetPoint = workspace.coolpart

for i, part in pairs(workspace.Parts:GetChildren()) do
    local dist = (part.Position - targetPoint.Position).Magnitude

    if dist < currentDist then --Checks if the distance is lesser than the currentDistance set.
        currentTarget = part --Sets the target
        currentDist = dist --Sets the currentDist to the new Distance
    end
end
print(currentTarget)

If it worked, please mark it as the solution.

2 Likes

If coolpart is moving use a linear search. If it’s static (but the part itself changes) you could use an octree/kd-tree (but probably still use linear search).