computeVelocity function

Offset computeVelocity(
  1. Offset currentVelocity,
  2. Offset defaultVelocity,
  3. double speedThreshold
)

Implementation

Offset computeVelocity(
  Offset currentVelocity,
  Offset defaultVelocity,
  double speedThreshold,
) {
  // Calculate the squared magnitude to avoid expensive sqrt calls for threshold check
  final double currentSpeedSq = currentVelocity.distanceSquared;
  final double defaultSpeedSq = defaultVelocity.distanceSquared;

  // Approximation for speed difference check to avoid sqrt
  // If squared difference is small enough, we can assume speeds are close
  if ((currentSpeedSq - defaultSpeedSq).abs() < speedThreshold * speedThreshold) {
    return defaultVelocity;
  }

  // Calculate actual speeds only when needed for scaling
  final double currentSpeed = currentVelocity.distance;
  final double defaultSpeed = defaultVelocity.distance;

  // If the difference in speed is less than the threshold, snap to the default velocity.
  if ((currentSpeed - defaultSpeed).abs() < speedThreshold) {
    return defaultVelocity;
  } else {
    // Decay factor controls how quickly the velocity returns to default.
    const decayFactor = 0.985;

    // Scale factor adjusts the default velocity to match the current speed's direction.
    final double scaleFactor = defaultSpeed / currentSpeed;

    // Target velocity is the default velocity scaled to match the current speed.
    final Offset targetVelocity = defaultVelocity * scaleFactor;

    // Interpolation amount determines how much to blend between current and target velocity.
    const double powrFactor = 0.989;
    final double interpolationAmount = powrFactor - decayFactor;

    // Smoothly interpolate from currentVelocity to targetVelocity.
    return Offset.lerp(currentVelocity, targetVelocity, interpolationAmount) ??
        currentVelocity;
  }
}