ik method

ArmAngles? ik(
  1. Size size,
  2. Offset relative
)

Performs inverse kinematics to get the angles of the arm from the desired position.

Implementation

ArmAngles? ik(Size size, Offset relative) {
  const a = shoulderLength / totalArmLength;
  const b = elbowLength / totalArmLength;
  final c = sqrt(pow(relative.dy, 2) + pow(relative.dx, 2));
  final b1Numerator = pow(a, 2) - pow(b, 2) + pow(c, 2);
  final b1Denominator = 2 * a * c;
  final b1 = acos(b1Numerator / b1Denominator);
  final b2 = atan2(relative.dy, relative.dx);
  final shoulder = b1 + b2;
  final cNumerator = pow(a, 2) + pow(b, 2) - pow(c, 2);
  const cDenominator = 2 * a * b;
  final elbow = acos(cNumerator / cDenominator);
  if (shoulder.isNaN || elbow.isNaN) return null;
  return (
    shoulder: shoulder,
    elbow: elbow,
    lift: -1 * (shoulder + elbow) + pi,
  );
}