Perpendicular on a line from a given point

前端 未结 14 1636
名媛妹妹
名媛妹妹 2020-11-29 18:34

How can I draw a perpendicular on a line segment from a given point? My line segment is defined as (x1, y1), (x2, y2), If I draw a perpendicular from a point (x3,y3) and it

14条回答
  •  清酒与你
    2020-11-29 19:25

    You will often find that using vectors makes the solution clearer...

    Here is a routine from my own library:

    public class Line2  {
    
    Real2 from;
    Real2 to;
    Vector2 vector;
    Vector2 unitVector = null;
    
    
        public Real2 getNearestPointOnLine(Real2 point) {
            unitVector = to.subtract(from).getUnitVector();
            Vector2 lp = new Vector2(point.subtract(this.from));
            double lambda = unitVector.dotProduct(lp);
            Real2 vv = unitVector.multiplyBy(lambda);
            return from.plus(vv);
        }
    

    }

    You will have to implement Real2 (a point) and Vector2 and dotProduct() but these should be simple:

    The code then looks something like:

    Point2 p1 = new Point2(x1, y1);
    Point2 p2 = new Point2(x2, y2);
    Point2 p3 = new Point2(x3, y3);
    Line2 line = new Line2(p1, p2);
    Point2 p4 = getNearestPointOnLine(p3);
    

    The library (org.xmlcml.euclid) is at: http://sourceforge.net/projects/cml/

    and there are unit tests which will exercise this method and show you how to use it.

    @Test
    public final void testGetNearestPointOnLine() {
        Real2 p = l1112.getNearestPointOnLine(new Real2(0., 0.));
        Real2Test.assertEquals("point", new Real2(0.4, -0.2), p, 0.0000001);
    }
    

提交回复
热议问题