nastaseion
nastaseion

Reputation: 173

Point to Line distance (2D) and Coordintates of intersection

So I need to know the Distance from a point to a line (in 2D space), given two coordinates of the line (AB).

Here is what I have so far:

public double pointToLineDistance(Point A, Point B, Point P)
{
    double normalLength = Math.sqrt((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y));
    return Math.abs((P.x - A.x) * (B.y - A.y) - (P.y - A.y) * (B.x - A.x)) / normalLength;
}

But I also need to get the coordinates of the point where the perpendicular line intersects with the AB line (it's ok if it's outside this segment).

Any ideas?

Upvotes: 0

Views: 3297

Answers (3)

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

Observe that AB can just be expressed as

ab = A + (B - A) * s

So, the direction of AB is B - A, or (B.x - A.x, B.y - A.y). A line whose direction is (A.y - B.y, B.x - A.x) will be perpendicular. (We just swap the x and y and negate one of them.)

We specifically want a line which is perpendicular to AB and also passes through P, so we do

perp = P + (A.y - B.y, B.x - A.x) * t;
perp = (P.x + A.y - B.y, P.y + B.x - A.x) * t;

Now just find the intersection between this perpendicular line and AB. You have two equations (for the x and y components of the intersection point) and two unknowns (s and t). Once you find s and t, plug them in to either of the lines' equations to get the intersection point.

Here is some working code:

static Vect2 getIntersection(Vect2 A, Vect2 B, Vect2 P) {
    Vect2 abDir = B.minus(A);
    Vect2 perpDir = new Vect2(-abDir.y, abDir.x);
    Vect2 apDir = P.minus(A);
    double s = (perpDir.y * apDir.x - perpDir.x * apDir.y)
             / (abDir.x * perpDir.y - abDir.y * perpDir.x);
    return A.plus(abDir.scale(s));
}

class Vect2 {
    final double x, y;

    Vect2(double x, double y) {
        this.x = x;
        this.y = y;
    }

    Vect2 scale(double k) {
        return new Vect2(x * k, y * k);
    }

    Vect2 plus(Vect2 that) {
        return new Vect2(x + that.x, y + that.y);
    }

    Vect2 minus(Vect2 that) {
        return this.plus(that.scale(-1));
    }
}

Upvotes: 2

jajo87
jajo87

Reputation: 1388

This would help http://paulbourke.net/geometry/pointline/

Upvotes: 1

zvrba
zvrba

Reputation: 24574

The idea is to construct an equation of the line going through the points A and B. When you have constructed that equation, you construct an equation of a line that goes through P and is perpendicular to AB. The equation for the perpendicular has coefficients that are easily derived from the equation for the AB-line. Once you have two equations, solving them will give you the coordinate of the intersection.

Is this for homework?

Upvotes: 1

Related Questions