Search code examples
javascriptvectortrigonometry

Find distance between 2D point and line segment start point


This feels like a simple problem but I am bad at algebra.

enter image description here

I'm trying to find the distance between a point and the start of a line segment at an angle parallel to the segment. I will use the distance to interpolate a value along the line.

I also need to know when the points are outside of the line.

A code example would be appreciated, this is my attempt so far using threejs Vector2D but it isn't behaving as expected.

const lineStartOrig = lineStart.clone()

const lineLength = lineStart.distanceTo(lineEnd)

const dotDiff = point2D.sub(lineStart).dot(lineEnd) / lineEnd.dot(lineEnd)


const pointIntersect = dummyLineStart.add(lineEnd)
                                     .multiplyScalar(dotDiff)
                                     .clamp(lineStartOrig, lineEnd)

const value = pointIntersect.distanceTo(lineStartOrig) / lineLength

Solution

  • In case it's useful to anyone, I used the following functions (unfortunately not in .js, but should illustrate the idea)

    To calc angle between two vectors and a test point C:

    float calcAngle(QVector2D& A, QVector2D& B, QVector2D& C)
    {
        QVector2D v1 = B - A;
        QVector2D v2 = C - A;
        float v1DotV2 = QVector2D::dotProduct(v1, v2);
        float magV1TimesMagV2 = v1.length()* v2.length();
        float cosTheta = v1DotV2/magV1TimesMagV2;
        float theta = qRadiansToDegrees(acosf(cosTheta));
        qInfo() << "Theta " << theta;
    
        return theta;
    }
    

    To get the distance and intersect point which I think the OP is after:

    float calcDistAlongParallelLineAndIntersectPoint(const QVector2D& A, const QVector2D& B, const QVector2D& C, QVector2D& intersectPoint)
    {
        QVector2D v1 = B - A;
        QVector2D v2 = C - A;
        float v1DotV2 = QVector2D::dotProduct(v1, v2);
        float magV1TimesMagV2 = v1.length()* v2.length();
        float cosTheta = v1DotV2/magV1TimesMagV2;
        float dist = v2.length() * cosTheta;
    
        QVector2D intersectingPoint = C - v1*(dist/v1.length());
        intersectPoint.setX(intersectingPoint.x());
        intersectPoint.setY(intersectingPoint.y());
        return dist;
    }
    

    A little check for some random points gives: enter image description here