moveTowards method

Vector2D moveTowards(
  1. Vector2D target,
  2. double maxDistance
)

Implementation

Vector2D moveTowards(Vector2D target, double maxDistance) {
  final dx = target.x - x;
  final dy = target.y - y;
  final value = (dx*dx) + (dy*dy);

  if (
    (value == 0) ||
    ((maxDistance >= 0) && (value <= maxDistance*maxDistance))
  ) return target;

  final dist = math.sqrt(value);

  return .vec2(
    x + dx/dist*maxDistance,
    y + dy/dist*maxDistance,
  );
}