Drawing a line between 2 points in 2D Space, Gui

I’m aware about this post: Drawing a line between two points in 2D?
But how am i supposed to do it?

local x1 = 0.941
local y1 = 0.248
local x2 = -0.024
local y2 = 3.777

I currently have this code, but I have no idea how to connect each one to each other. How would i do this?


I understand it but have no idea how to implement it.

1 Like
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

Source: Drawing a line between two points in 2D? - #6 by GamerJanko

1 Like

What do i put in pointA and pointB?

(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)

nevermind, found it

1 Like

wait, which value do i do from the absolute position, i’m confused :skull:

local GuiObjectA = nil 
local GuiObjectB = nil

local VectorA = Vector2.new(GuiObjectA.AbsolutePosition.X, GuiObjectA.AbsolutePosition.Y)
local VectorB = Vector2.new(GuiObjectB.AbsolutePosition.X, GuiObjectB.AbsolutePosition.Y)

DrawLine(VectorA, VectorB, Parent)

Set GuiObjectA/B as the path of the GuiObjects

1 Like

I’ve made this same exact thing in my “Implementing 2D raycasting topic
Here is the code, place it inside a ModuleScript:

local parent = script.Parent.Parent

local function draw(length, frame)
	local line = frame or Instance.new("Frame")
	line.Name = "line"
	line.AnchorPoint = Vector2.new(.5, .5)
	line.Size = UDim2.new(0, length, 0, 2)
	line.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
	line.BorderSizePixel = 0
	line.ZIndex = 1
	line.Parent = parent
	
	return line
end

return function (originX, originY, endPointX, endPointY, frame)
	local origin = Vector2.new(originX, originY)
	local endPoint = Vector2.new(endPointX, endPointY)
	local netVector = endPoint - origin
	
	local length = math.sqrt(netVector.X ^ 2 + netVector.Y ^ 2)
	local midpoint = Vector2.new((origin.X + endPoint.X) / 2, (origin.Y + endPoint.Y) / 2)
	local theta = math.deg(math.atan2(originY - endPointY, originX - endPointX))
	
	local line = draw(length, frame)
	line.Position = UDim2.fromOffset(midpoint.X, midpoint.Y)
	line.Rotation = theta
	
	return line
end

Edit it as you desire

1 Like

Worked so well, thanks so much. I have one of the smoothest lines now :slight_smile: Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.