Drawing a line between two points in 2D?

Now that we have rotation for GUI objects, it’s always questioned me what the math would be to draw a straight line between two points on a GUI
image enjoy my beautiful paint skills

Obviously, in 3D we have a few CFrame functions to do it, but these functions dont exist in 2D. I’m not asking how to do curved lines because that would take multiple frames

1 Like

This is my first post so please be patient.


I’ll be referencing (x1,y1) and (x2,y2) as shown in the picture.

First we need a frame that is the width of the line you want and the length of the distance between the two points. Thus we have a frame with breadth of sqrt((x1-x2)^2+(y1-y2)^2) and a height of ~1 (or however thick you want your line to be).

Next we need to align that frame in the middle of the two points. To do that we set the anchor point to {0.5,0.5} and then set the frame’s x,y to ((x1+x2)/2,(y1+y2)/2).

Finally you need to rotate the frame so it matches with the other point. Using some trig you can find that you should rotate the frame atan2((y1-y2),(x1-x2)).

Hope that helps!

20 Likes

When setting the frame’s x and y, it is the position right? Not the size? And also, how do we find the x1, x2, y1, y2 values?

From my understanding, x1/2 and y1/2 are placeholders for any values you’d like to input. It is referring to the position of different points & not the size, as shown through the image that they uploaded.

2 Likes

This makes a lot more sense. Now I realize I’m just dumb… :sweat_smile:

2 Likes

I’m a little late to the party but,

I also just want to note, the rotation of ‘atan2((y1-y2),(x1-x2))’ should be converted to degrees with the ‘math.deg()’ function. Took me way to long to figure that out

Anyway, I made a simple function to draw a line between 2 points using the logic @scotch101tape said (Point A and Point B should be Vector2’s in pixels from the top left corner of the screen, aka the AbsolutePosition of a UI object)

local function DrawLine(PointA, PointB, Parent)
	local Distance = math.sqrt(math.pow(PointA.X-PointB.X, 2) + math.pow(PointA.Y-PointB.Y, 2))
	local Center = Vector2.new((PointA.X + PointB.X)/2, (PointA.Y + PointB.Y)/2)	
	local Rotation = math.atan2(PointA.Y - PointB.Y, PointA.X - PointB.X)
	local LineThickness = 4
	
	local Line = Instance.new("Frame")
	Line.Size = UDim2.new(0, Distance, 0, LineThickness)
	Line.AnchorPoint = Vector2.new(0.5,0.5)
	Line.Position = UDim2.new(0, Center.X, 0, Center.Y)
	Line.Rotation = math.deg(Rotation)
	Line.Parent = Parent
end
10 Likes