projectPoint method

ProjectionResult projectPoint(
  1. Vec2D point, {
  2. bool clamp = true,
})

Find where the given point lies on this segment.

Implementation

ProjectionResult projectPoint(Vec2D point, {bool clamp = true}) {
  _computeDiff();
  if (lengthSquared == 0) {
    return ProjectionResult(0, start);
  }
  double t = ((point.x - start.x) * (end.x - start.x) +
          (point.y - start.y) * (end.y - start.y)) /
      lengthSquared;

  if (clamp) {
    // Clamp at edges.
    if (t < 0.0) {
      return ProjectionResult(0, start);
    }
    if (t > 1.0) {
      return ProjectionResult(1, end);
    }
  }

  return ProjectionResult(
    t,
    Vec2D.fromValues(
      start.x + t * (end.x - start.x),
      start.y + t * (end.y - start.y),
    ),
  );
}