I’m not too sure what’s going on in that function so I can’t really modify it, but I came up with this typed function which should be what you’re looking for:
function FindLineIntersection2D(l1p1: Vector2, l1p2: Vector2, l2p1: Vector2, l2p2: Vector2, l1Seg: boolean?, l2Seg: boolean?): Vector2?
local a1: number = l1p2.Y - l1p1.Y
local b1: number = l1p1.X - l1p2.X
local a2: number = l2p2.Y - l2p1.Y
local b2: number = l2p1.X - l2p2.X
local c1: number = a1 * l1p1.X + b1 * l1p1.Y
local c2: number = a2 * l2p1.X + b2 * l2p1.Y
local determinant: number = a1 * b2 - a2 * b1
if (determinant == 0) then
return -- lines are parallel
end
local x: number = (b2 * c1 - b1 * c2) / determinant
local y: number = (a1 * c2 - a2 * c1) / determinant
if (l1Seg or l2Seg) then
if l1Seg and not (math.min(l1p1.X, l1p2.X) <= x
and x <= math.max(l1p1.X, l1p2.X)
and math.min(l1p1.Y, l1p2.Y) <= y
and y <= math.max(l1p1.Y, l1p2.Y))
or l2Seg and not (math.min(l2p1.X, l2p2.X) <= x
and x <= math.max(l2p1.X, l2p2.X)
and math.min(l2p1.Y, l2p2.Y) <= y
and y <= math.max(l2p1.Y, l2p2.Y)) then
return -- lines dont intersect
end
end
return Vector2.new(x, y)
end
If you want the function to take the lengths of the lines or one of the lines into account, simply pass l1Seg
and l2Seg
as true
respectively.
Test code
function V3ToV2(vector: Vector3): Vector2
-- ignore Y component
return Vector2.new(vector.X, vector.Z)
end
local l1, l2 = workspace.l1, workspace.l2
local p: Part = Instance.new("Part")
p.Shape = Enum.PartType.Ball
p.Anchored = true
p.Parent = workspace
p.Size = Vector3.new(2, 2, 2)
task.spawn(function()
while task.wait() do
local p1, p2, p3, p4 =
(l1.CFrame * CFrame.new(0, 0, -l1.Size.Z/2)).Position,
(l1.CFrame * CFrame.new(0, 0, l1.Size.Z/2)).Position,
(l2.CFrame * CFrame.new(0, 0, -l2.Size.Z/2)).Position,
(l2.CFrame * CFrame.new(0, 0, l2.Size.Z/2)).Position
local point = FindLineIntersection2D(V3ToV2(p1), V3ToV2(p2), V3ToV2(p3), V3ToV2(p4), true, true)
p.Transparency = point and 0 or 1
if point then
p.Position = Vector3.new(point.X, p1.Y, point.Y)
end
end
end)