I’m creating a train system where the carts move along a path, however the distance between the carts changes along the path due to the distance between each point not being constant
Thought of a solution. Mark the first part. Create a table that orders the parts from distance from that labelled part. Use tables to keep track of lookvectors (so the angle stays the same). Then loop through the parts table and set new parts accordingly. Here’s a basic demo
local parts = workspace.parts
local p1 = parts.p1
local goalDistance = 5 -- Desired distance between parts
local info = {}
local indexes = {}
local directionVectors = {}
local partTable = parts:GetChildren()
for i,v in ipairs(partTable) do
info[#info+1] = {v, (v.Position - p1.Position).Magnitude}
indexes[#indexes + 1] = i
end
local comparisons = #parts:GetChildren() - 1
-- Bubble sort; ordering parts by distance
for a = 1,comparisons do
for i = 1,comparisons do
if info[i+1][2] < info[i][2] then
-- Switching parts
local temp = info[i][2]
info[i][2] = info[i+1][2]
info[i+1][2] = temp
-- Using an index table to keep track of what parts are being switched
local temp2 = indexes[i]
indexes[i] = indexes[i+1]
indexes[i+1] = temp2
end
end
end
-- Creating direction vector table
for b = 1,comparisons do
directionVectors[#directionVectors + 1] = partTable[indexes[b+1]].Position - partTable[indexes[b]].Position
end
for c = 1,comparisons do
local directionVector = directionVectors[c]
local scaleFactor = goalDistance/directionVector.Magnitude
partTable[c+1].Position = partTable[c].Position + scaleFactor * directionVector -- Set position of part
end