Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LineSegment intersection returning nil incorrectly #20

Open
AndrewHartAR opened this issue Feb 3, 2020 · 0 comments
Open

LineSegment intersection returning nil incorrectly #20

AndrewHartAR opened this issue Feb 3, 2020 · 0 comments

Comments

@AndrewHartAR
Copy link

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))
        }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant