Search code examples
c3dgeometrylinepoints

Extending a line between 2 points in 3D space


Let's say I have 2 points in 3D space, one at:

x=2, y=3, z=5

and the second one at:

x=6, y=7, z=10

What is the fastest way, in code, to calculate the coordinates of a third point from extending (for example, doubling) the distance between those two points (relative to point one)?


Solution

  • If you want a point extended as far beyond (x2,y2,z2) as that is beyond (x1,y1,z1):

    x3 = x2 + (x2 - x1) (= 10)
    y3 = y2 + (y2 - y1) (= 11)
    z3 = z2 + (z2 - z1) (= 15)
    

    or:

    (x2 * 2 - x1, y2 * 2 -y1, z2 * 2 - z1)
    

    Simple as that.

    If you want something other than double the length, you can scale the (x2 - x1)-type terms. For example, if you want it 50% longer than the current line, multiply them by 0.5 (+50%). If you want it three times longer, multiply them by two (+200%).

    In terms of code that can perform this extension, something like this, which gives you an endpoint pDest that, along with, p1 forms a line percent times the size of p1-p2:

    typedef struct {
        double x;
        double y;
        double z;
    } tPoint3d;
    
    void extend (tPoint3d *p1, tPoint3d *p2, double percent, tPoint3d *pDest) {
        percent -= 100.0;                             // what to ADD
        percent /= 100.0;                             // make multiplier
        pDest->x = p2->x + percent * (p2->x - p1->x); // scale each point
        pDest->y = p2->y + percent * (p2->y - p1->y);
        pDest->z = p2->z + percent * (p2->z - p1->z);
    }