Compute if orthogonal through Point P intersects a line segment defined by its endpoints

Viewed 39

Assume a line is defined through its endpoints begin and end. Suppose P is another point

enter image description here

I'm in search of a method, which returns true iff. the orthogonal of Line(A,B) through target cuts Line(A,B) between A and B.

This method computes the length of a line:

  static double lengthOfLine(Offset a, Offset b ) {
    double length = math.sqrt( ( b.dx - a.dx )*( b.dx - a.dx ) + ( b.dy - a.dy ) * ( b.dy - a.dy ) );
    return length;
  }

And this function the distance between target and the indefinite long line defined by begin and end:

  static double shortestDistance(Offset begin, Offset end, Offset target) {

    double legnthOfLine = lengthOfLine( begin, end );

    double a = end.dy - begin.dy;
    double b = begin.dx - end.dx;
    double c = end.dx * begin.dy - begin.dx * end.dy;

    double q = a * target.dx + b * target.dy + c;
    if ( 0.0 > q ) {
      q = -1.0 * q;
    }

    return q / legnthOfLine;

  }

I just want to know, if the othogonal relative to Line(begin, end) through target cuts Line(begin, end) within begin and end.

1 Answers

Does this work?

static bool perp_intersects_segment(Offset start, Offset end,  Offset target ) {

    double start_end_x = end.dx - start.dx;
    double start_end_y = end.dy - start.dy;
    double dot_product = start_end_x * (target.dx - end.dx) 
                       + start_end_y * (target.dy - end.dy);

    dot_product = ( start_end_x * (target.dx - start.dx) 
                  + start_end_y * (target.dy - start.dy)
                  ) * dot_product;

    return ( dot_product <= 0.0 );

}
Related