Searching for closest attachment doesn't work for the first attachment but second

Hello,

I am trying to make a wiring system and I’ve encountered a problem.

When you click on the ground or somewhere a Attachment gets created in a Part in a folder called WireSystem.

I want the attachment to automatically search for closest Attachment to position to.
It works for the second attachment but not the first attachment.

Code:

if Attachment1 == nil and Attachment2 == nil and Target ~= nil then
    Hit, Target, _ =
        Mouse:ProjectMouseRay({localPlayer.Character, Attachment1, Attachment2, rodConstraint, PartConnector})
    PartConnector = Instance.new("Part", workspace.WireSystem)
    PartConnector.Name = "Wire"
    PartConnector.Size = Vector3.new(0.5, .5, .5)
    PartConnector.Transparency = 1
    PartConnector.CanCollide = false
    PartConnector.Anchored = true
    PartConnector.CFrame = Hit

    local newAttachment = Instance.new("Attachment", PartConnector)
    newAttachment.Name = "First"
    newAttachment.Visible = true

    closestAttachment = nil
    for _, wires in pairs(workspace.WireSystem:GetChildren()) do -- This is the for loop that checks for closest attachment
        for _, attachment in pairs(wires:GetChildren()) do
            if not attachment:IsA("RodConstraint") and attachment:IsA("Attachment") then
                local magnitude = (attachment.WorldPosition - Hit.p).magnitude
                if magnitude <= 1 then
                    closestAttachment = attachment
                    break
                end
            end
        end
    end

    if closestAttachment ~= nil then
        newAttachment.WorldPosition = closestAttachment.WorldPosition
    elseif closestAttachment == nil then
        newAttachment.WorldPosition = Hit.p
    end

    Attachment1 = newAttachment
    closestAttachment = nil

    return true
end

It is the same for the second attachment too.

But it only works for the second attachment.

Thanks in advance. :slightly_smiling_face:

Edit: Solved

1 Like

That code of yours does not find the ‘closest attachment’, instead it finds ‘whatever attachment that has a distance no more than 1 stud away from Hit.Position’.

You need to loop through all attachments, find their distances (magnitude) and discard any previous found distance (and attachment) when finding an even closer one.

local closestDistance = math.huge
local closestAttachment = nil
for _,attachment in ipairs( GetChildren() ) do
  local magnitude = (attachment.WorldPosition - Hit.Position).magnitude
  if magnitude < closestDistance then
    closestDistance = magnitude  -- <---
    closestAttachment = attachment
  end
end

Hmm… Ninja’ed by OP :smile:

1 Like