Get closest part to other part in folder

helllo. i am trying to get the closest part to the First_Spawn. the First_Spawn is in the same folder than all the others. somehow i sapwn on a distanced seat sometimes. how to fix?

			for a, b in ipairs(ChosenHouse.SEATS:GetChildren()) do
				if b == First_Spawn then continue end
				local dist = (b.Position-b.Position).Magnitude

				if dist < closestDist then
					closestPart = b; closestDist = dist end
			end
3 Likes

You need to check distance between First_Spawn and the part, you are checking the distance between the part and itself which always returns 0.

local dist = (First_Spawn.Position-b.Position).Magnitude
3 Likes

Are you trying to get the part that’s closest to any part in a folder?

3 Likes
local ClosestPart = nil

for i, parts in pairs(ChosenHouse.SEATS:GetChildren()) do
   if ClosestPart ~= nil then
      if parts.Magitude > ClosestPart.Magitude then
         ClosestPart = parts
      end
  else
      ClosestPart = parts
   end
end

This will get all parts in the folder, if the ClosestPart variable is not nil, then it will check if parts.Magitude is bigger then ClosestPart.Magitude, if it is then ClosestPart will update to the part selection, elseif it is nil, then ClosestPart will automatically turn into parts.

3 Likes

fr now? wait a minute… was i that stupid… let me check…

EDIT: yes i was.

1 Like

now i only need to check that the closestpart isnt the first spawn and if it is, continue to search for the closest part. how i do so? the one that answers this question gets the solution

2 Likes

The code you already have should work for it, if not then maybe try checking if b.Name == "First_Spawn".

1 Like

but how do i continue searching for a suitablke one if it is the first spawn?

1 Like

im trying to ge the closest to the First_Spawn that IS NOT THE FIRST SPAWN ITSELF

1 Like

if b == First_Spawn then continue end will skip to the next part if b is First_Spawn.

image
why so far away???

What are closestPart and closestDist set to before the loop? You should set them both to nil and then when the loop starts make sure first part gets set as the closest:

if not closestDist then
    closestPart = b
    closestDist = dist
    continue
end

This goes after declaring dist.

They are both. Is there anything else you would like to know?

You should try what i said in previous post and if it doesnt work can you show how the code looks currently?

Use this method like bruh you never even used it

local FirstS = First_Spawn.Position
local ClosestD = math.huge
local ClosetP = First_Spawn


for a,b in ipairs(ChosenHouse.SEATS:GetChildren()) do
  if b == First_Spawn then
  continue
 end
  
  local dis = (FirstS.Position - b.Position).Magnitude
  
  if ClosestD > dis then
   
   ClosestP = b
   ClosestD = dis

  end
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.