Intersection between two lines in coordinates

后端 未结 6 1672
臣服心动
臣服心动 2020-12-31 19:42

I can detect the intersection point of two lines, but if my line don\'t has the length of my screen, it detects the point, where it shouldn\'t be.

Here a preview:

6条回答
  •  有刺的猬
    2020-12-31 20:14

    Swift version

    func getIntersectionOfLines(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("error, parallel lines")
                return CGPointZero
            }
    
            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("error, intersection not inside line1")
                return CGPointZero
            }
            if (v < 0.0 || v > 1.0) {
                print("error, intersection not inside line2")
                return CGPointZero
            }
    
            return CGPointMake(line1.a.x + u * (line1.b.x - line1.a.x), line1.a.y + u * (line1.b.y - line1.a.y))
        }
    

提交回复
热议问题