How to Make a Line Between Two Parts

I wanted to make a line connecting two parts for an upcoming project and was disappointed to find every post used CFrame-based methods that I simply could not get to work. Thus, I did some basic algebra and trig (I’m too lazy explain the math that goes on behind it) and got this code! Tested with quite a few conditions, this should work for any iteration. Here’s the code:

local function make_line(a : Vector3, b : Vector3)
	local x = math.abs((a.X-b.X)/2)+math.min(a.X, b.X)
	local y = math.abs((a.Y-b.Y)/2)+math.min(a.Y, b.Y)
	local z = math.abs((a.Z-b.Z)/2)+math.min(a.Z, b.Z)
	
	local magnitude = (a-b).Magnitude
	
	local XZ = math.deg(math.atan2((a.X-b.X), (a.Z-b.Z)))
	local Y = -math.deg(math.atan2((a.Y-b.Y), math.sqrt(math.pow(math.abs((a.X-b.X)),2)+math.pow(math.abs((a.Z-b.Z)),2))))
	
	local line = Instance.new("Part")
	line.Anchored = true
	line.Size = Vector3.new(1,1,magnitude)
	line.Position = Vector3.new(x, y, z)
	line.Orientation = Vector3.new(Y, XZ, 0)
	return line
end

local test = make_line(workspace.test1.Position, workspace.test2.Position)
test.Parent = workspace

Result:

5 Likes

This is an easier way

function make_line(pos1, pos2)
	local part = Instance.new("Part")
	local distance = (pos1 - pos2).Magnitude
	local offset = CFrame.new(0, 0, -distance / 2)
	part.Size = Vector3.new(part.Size.X, part.Size.Y, distance) 
	part.CFrame = CFrame.new(pos1, pos2) * offset
	part.Anchored = true
	part.Parent = workspace
end

10 Likes

at least this doesn’t require a ton of math knowledge unlike the original one. I will make a module using your method, thanks!

1 Like