segmentSquaredDistance static method

double segmentSquaredDistance(
  1. Vec2D segmentPoint1,
  2. Vec2D segmentPoint2,
  3. Vec2D pt
)

Implementation

static double segmentSquaredDistance(
    Vec2D segmentPoint1, Vec2D segmentPoint2, Vec2D pt) {
  double t = onSegment(segmentPoint1, segmentPoint2, pt);
  if (t <= 0) {
    return Vec2D.squaredDistance(segmentPoint1, pt);
  }
  if (t >= 1) {
    return Vec2D.squaredDistance(segmentPoint2, pt);
  }

  Vec2D ptOnSeg = Vec2D.fromValues(
    segmentPoint1.x + t * (segmentPoint2.x - segmentPoint1.x),
    segmentPoint1.y + t * (segmentPoint2.y - segmentPoint1.y),
  );

  return Vec2D.squaredDistance(ptOnSeg, pt);
}