0

I found something similar that gave me the general form of a line but after writing it out I came across some limitations with horizontal/vertical lines. Source here: https://math.stackexchange.com/questions/637922/how-can-i-find-coefficients-a-b-c-given-two-points

I'm not that good with math but I assume there are restrictions of the general equation of a line formula and attempting to calculate the distance with the distance formula using general coefficients of A,B,C did not work out.

Here's my original code that got the coefficients.

func computeEquationOfALineCoefficients(point1: CGPoint, point2: CGPoint) -> [CGFloat] {
    // Computes the equation of a line in the form Ax + By + C = 0 thorugh
    // y - y1 = (y2 - y1)/(x2 - x1) * (x - x1) or alternatively
    // (y1-y2) * x + (x2-x1) * y + (x1-x2)*y1 + (y2-y1)*x1 = 0
    // where a = y1 - y2, b = x2 - x1, c = (x1-x2)*y1 + (y2-y1)*x1
    let x1: CGFloat = point1.x
    let x2: CGFloat = point2.x
    let y1: CGFloat = point1.y
    let y2: CGFloat = point2.y

    let A = y1 - y2
    let B = x2 - x1
    let C = (x1 - x2) * y1 + (y2 - y1) * x1

    return [A, B, C]
}

and then the distance formula I was using

func computeDistanceBetweenPointAndLine(point: CGPoint, A: Float, B: Float, C: Float) -> Float {
    let x: Float = Float(point.x)
    let y: Float = Float(point.y)

    let distance = abs(A * x + B * y + C) / (pow(A, 2) + pow(B, 2)).squareRoot()

    return distance
}

it works fine until I introduce a horizontal line like the coordinates 0,0 and 150,0.

So I then decided to try the route with the perpendicular intersection between a point and a line but I'm stumped at solving for x by setting two equations equal to each other. I found a resource for that here: https://sciencing.com/how-to-find-the-distance-from-a-point-to-a-line-13712219.html but I am not sure how this is supposed to be represented in code.

Any tips or resources I may have yet to find are appreciated. Thank you!

Paul
  • 1,101
  • 1
  • 11
  • 20

0 Answers0