Automatic connection between 2 objects with attachment

I have been developing my construction system for several days, today I had a problem, I am trying to bring an object closer to another of the same category so that they join together, I don’t really understand why it misaligns when I move it away. If anyone has any advice, please don’t hesitate to tell me. :smiley:

local o:Model = selections[1]

if autoAttachment and o:GetAttribute("type") == 2 then

   local anchoredTo = nil
   local attch0:Attachment = o.selectionPart:FindFirstChild("Attachment0")
   local attch1:Attachment = o.selectionPart:FindFirstChild("Attachment1")

   if attch0 and attch1 then

      local o:Part = o.selectionPart

      local displacement = attch0.WorldPosition - attch1.WorldPosition
      local returnTable = workspace:GetPartBoundsInBox(o:GetPivot(), Vector3.new(o.Size.X * 1.5, o.Size.Y + 2, o.Size.Z * 1.5), nil)

      for _, p in returnTable do

         if anchoredTo == nil and p:IsA("BasePart") and p.Name == "selectionPart" and p.Parent:GetAttribute("type") == 2 then

            warn("Connect")
            anchoredTo = p.Parent
            local attch2:Attachment = p:FindFirstChild("Attachment0")
            local attch3:Attachment = p:FindFirstChild("Attachment1")
            local CF = attch2.WorldCFrame + ((attch0.WorldPosition - attch1.WorldPosition)/2)

            o.Parent:SetPrimaryPartCFrame(CF)
            warn("connected to:", anchoredTo)
         end

      end

      if (mouse.Hit.Position - o.Parent:GetPivot().Position).Magnitude >= 2.5 then
         warn("Disconect")
         anchoredTo = nil
         placeSelection(b)
      end


   else
      placeSelection(b)
   end
else

   placeSelection(b)

end
1 Like