Here you can find the source of distanceToLine(Point2D p, Point2D endA, Point2D endZ)
Parameter | Description |
---|---|
p | point, distance from which is to be calculated |
endA | one end of the line |
endZ | the other end of the line |
public static double distanceToLine(Point2D p, Point2D endA, Point2D endZ)
//package com.java2s; import java.awt.geom.Point2D; public class Main { /**/* w w w.j a v a 2s . c o m*/ * Computes distance from a point on a plane to line given by two points. * * @param p point, distance from which is to be calculated * @param endA one end of the line * @param endZ the other end of the line * @return distance from p to line, formed by endA and endZ */ public static double distanceToLine(Point2D p, Point2D endA, Point2D endZ) { /* Geometry here is: * - A and B are points on ends of the line * - C is a point, distance from which to AB is to be calculated * - D is a point on AB, such that CD is perpendicular to AB. * We need to find length of CD. Composing a system of equations: * - AC squared = AD squared + CD squared (ACD is a right triangle) * - BC squared = BD squared + CD squared (BCD is also a right triangle) * - AD + BD = AB (D is on AB) * it's solution is obvious from the code :-) */ double AC = p.distance(endA); double BC = p.distance(endZ); double AB = endA.distance(endZ); if (AB == (AC + BC)) { return 0; } double ACs = AC * AC; double BCs = BC * BC; double AD_BD = (ACs - BCs) / AB; double AD = (AD_BD + AB) / 2; double CDs = ACs - (AD * AD); return Math.sqrt(CDs); } }