Help making parts move parallel to one another

  1. What do you want to achieve? I want all the parts from the “From” folder to move all in the same direction parallel to each other to a given parts position in the “To” folder.

  2. What is the issue? Sometimes a part is a little closer than another which causes some parts to cross each other when moving.

  3. What solutions have you tried so far? I tried to get the closest part between From and To, and I also tried to get the average positions of the “To” parts and “From” parts but that wouldn’t work because if a single “From” part is far from the rest of the parts it could change the whole average position.

Below is what I want to happen.

Here is my current code:

local From = workspace.From:GetChildren()
local To = workspace.To:GetChildren()

local ToPositions = {}

for _, ToPart in pairs(To) do
	table.insert(ToPositions, ToPart.Position)
end

for _, ToPosition in pairs(ToPositions) do
	
	local ClosestFromPart = nil
	local Magnitude = 999999
	
	for _, FromPart in pairs(From) do
		if (FromPart.Position - ToPosition).Magnitude < Magnitude then
			ClosestFromPart = FromPart
			Magnitude = (FromPart.Position - ToPosition).Magnitude
		end
	end
	
	if ClosestFromPart then
		
		local NewFrom = {}
		
		for _, FromPart in pairs(From) do
			if FromPart ~= ClosestFromPart then
				table.insert(NewFrom, FromPart)
			end
		end
		
		From = NewFrom
		
		game:GetService("TweenService"):Create(ClosestFromPart, TweenInfo.new(2), {Position = ToPosition}):Play()
	end
end

It looks like you’re looping upon your ‘To’ and ‘From’ folders using an unordered array, causing some crossed wires. It is generally advisable to use ipairs when possible, mainly for its efficiency and order.

local From = workspace.From:GetChildren()
local To = workspace.To:GetChildren()

local ToPositions = {}

for _, ToPart in ipairs(To) do
	table.insert(ToPositions, ToPart.Position)
end

for _, ToPosition in ipairs(ToPositions) do
	
	local ClosestFromPart = nil
	local Magnitude = 999999
	
	for _, FromPart in ipairs(From) do
		if (FromPart.Position - ToPosition).Magnitude < Magnitude then
			ClosestFromPart = FromPart
			Magnitude = (FromPart.Position - ToPosition).Magnitude
		end
	end
	
	if ClosestFromPart then
		
		local NewFrom = {}
		
		for _, FromPart in ipairs(From) do
			if FromPart ~= ClosestFromPart then
				table.insert(NewFrom, FromPart)
			end
		end
		
		From = NewFrom
		
		game:GetService("TweenService"):Create(ClosestFromPart, TweenInfo.new(2), {Position = ToPosition}):Play()
	end
end

Hope this helps! :slight_smile:

This may work in some scenarios, but in this case I want it to move all of the parts parallel to one another no matter the order of the array.