Calculating distance between parts

Hello, I was wondering if it’s possible to calculate distance between parts to add certain amount parts in this distance with perfect spacing.

Here is example
Blue parts are start/end of distance.
Gray parts are positioned correctly from start to end with perfect spacing.

Here is 2 studs spacing.
image

Here is bad spacing and parts are not positioned correctly
image

I tried using a lot of math combinations but I got tired after 5 hours and I’m looking for help.

I asked my friends and they didn’t know too.

Do the amount of parts between the 2 blue parts matter? And does the size of the parts that will get in between matter? I might be able to help you out here

Oh… Do you mean that you can’t find a solution to adding parts between these 2 parts with a correct spacing, right?

Edit: Sorry, I didn’t read correct.

local blue1 = workspace.Blue1
local blue2 = workspace.Blue2
local gray = workspace.Gray

local distance = (blue1.Position - blue2.Position).Magnitude
local spacing = distance / 5 -- Divide the distance by the number of parts you want to add plus one

for i = 1, 4 do -- REMEMBER: 4 is the number of parts.
    local newGray = gray:Clone()
    newGray.Parent = workspace
    newGray.Position = blue1.Position - Vector3.new(0, 0, spacing * i)
end

Amount of parts between 2 blue parts can be random like 3 or 5. The size of the parts that will get in doesn’t matter. Part can be (1, 5, 2) or (5, 2, 1)

1 Like

Works fine but when you do it in opposite way

local distance = (blue2.Position - blue1.Position).Magnitude
-- rest of script

newGray.Position = blue2.Position - Vector3.new(0, 0, spacing * i)

then it completly brokes and parts are over blue2 part instead of being between these parts.
image

I’m making feature that player can select which part is first and second to calculate the distance to fit parts.
When players selects blue2 as first part then it calculates in that way I gave earlier

Here is my solution.

function generateParts(part1, part2, n)
    local direction = part2.Position - part1.Position
    local offset = direction.Magnitude / (n + 1)
    direction = direction.Unit
    local position = part1.Position
    for i = 1, n do
        local p = Instance.new("Part")
        p.Anchored = true
        p.CanCollide = false
        p.Position = position + offset * direction
        p.Parent = workspace
        position = p.Position
    end
end
generateParts(workspace.Part1, workspace.Part2, 5)