Extend a line segment a specific distance

后端 未结 3 1876
感动是毒
感动是毒 2020-12-05 04:52

I am trying to find a way to extend a line segment by a specific distance. For example if I have a line segment starting at 10,10 extending to 20,13 and I want to extend th

相关标签:
3条回答
  • 2020-12-05 05:11

    You can do it by finding unit vector of your line segment and scale it to your desired length, then translating end-point of your line segment with this vector. Assume your line segment end points are A and B and you want to extend after end-point B (and lenAB is length of line segment).

    #include <math.h> // Needed for pow and sqrt.
    struct Point
    {
        double x;
        double y;
    }
    
    ...
    
    struct Point A, B, C;
    double lenAB;
    
    ...
    
    lenAB = sqrt(pow(A.x - B.x, 2.0) + pow(A.y - B.y, 2.0));
    C.x = B.x + (B.x - A.x) / lenAB * length;
    C.y = B.y + (B.y - A.y) / lenAB * length;
    
    0 讨论(0)
  • 2020-12-05 05:16

    I just stumbled upon this after searching for this myself, and to give you an out-of-the-box solution, you can have a look at the code inside a standard Vector class (in any language) and cherry pick what parts you need, but I ended up using one and the code looks like this :

    vector.set(x,y);
    vector.normalize();
    vector.multiply(10000);// scale it by the amount that you want
    

    Good luck !

    0 讨论(0)
  • 2020-12-05 05:23

    If you already have the slope you can compute the new point:

    x = old_x + length * cos(alpha);
    y = old_y + length * sin(alpha);
    

    I haven't done this in a while so take it with a grain of salt.

    0 讨论(0)
提交回复
热议问题