Metron
Metron copied to clipboard
LineSegment intersection returning nil incorrectly
let lineSegment1 = Metron.LineSegment(a: CGPoint(x: 5.203594207763672, y: 3.6903457641601562), b: CGPoint(x: -9.671459197998047, y: 9.507403373718262))
let lineSegment2 = Metron.LineSegment(a: CGPoint(x: (3.9301047325134277), y: 3.930098295211792), b: CGPoint(x: 3.930110216140747, y: 8.778124809265137))
let intersection = lineSegment1.intersection(with: lineSegment2)
Intersection returns nil, when it should return as CGPoint(x: 3.9301050246323883, y: 4.18835808998847)
You can see these numbers on Desmos: https://www.desmos.com/calculator/aqc2syqz2s
I have another function in my project which does the same job, which may be able to give a hint as to why the Metron function isn't working properly:
extension CGPoint {
static func intersectionOfLines(line1: (a: CGPoint, b: CGPoint), line2: (a: CGPoint, b: CGPoint)) -> CGPoint? {
let distance = (line1.b.x - line1.a.x) * (line2.b.y - line2.a.y) - (line1.b.y - line1.a.y) * (line2.b.x - line2.a.x)
if distance == 0 {
print("intersection issue, parallel lines")
return nil
}
let u = ((line2.a.x - line1.a.x) * (line2.b.y - line2.a.y) - (line2.a.y - line1.a.y) * (line2.b.x - line2.a.x)) / distance
let v = ((line2.a.x - line1.a.x) * (line1.b.y - line1.a.y) - (line2.a.y - line1.a.y) * (line1.b.x - line1.a.x)) / distance
if (u < 0.0 || u > 1.0) {
print("intersection issue, intersection not inside line1")
return nil
}
if (v < 0.0 || v > 1.0) {
print("intersection issue, intersection not inside line2")
return nil
}
return CGPoint(
x: line1.a.x + u * (line1.b.x - line1.a.x),
y: line1.a.y + u * (line1.b.y - line1.a.y))
}
}