No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Limb.cs 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using UnityEngine.Scripting.APIUpdating;
  2. namespace UnityEngine.U2D.IK
  3. {
  4. /// <summary>
  5. /// Utility for 2D Limb IK Solver.
  6. /// </summary>
  7. [MovedFrom("UnityEngine.Experimental.U2D.IK")]
  8. public static class Limb
  9. {
  10. /// <summary>
  11. /// Solve based on Limb IK
  12. /// </summary>
  13. /// <param name="targetPosition">Target position.</param>
  14. /// <param name="lengths">Length of the chains.</param>
  15. /// <param name="positions">Chain positions.</param>
  16. /// <param name="outAngles">Output angles for the chain's position.</param>
  17. /// <returns>Always returns true.</returns>
  18. public static bool Solve(Vector3 targetPosition, float[] lengths, Vector3[] positions, ref float[] outAngles)
  19. {
  20. outAngles[0] = 0f;
  21. outAngles[1] = 0f;
  22. if (lengths[0] == 0f || lengths[1] == 0f)
  23. return false;
  24. var startToEnd = targetPosition - positions[0];
  25. var distanceMagnitude = startToEnd.magnitude;
  26. var sqrDistance = startToEnd.sqrMagnitude;
  27. var sqrParentLength = (lengths[0] * lengths[0]);
  28. var sqrTargetLength = (lengths[1] * lengths[1]);
  29. var angle0Cos = (sqrDistance + sqrParentLength - sqrTargetLength) / (2f * lengths[0] * distanceMagnitude);
  30. var angle1Cos = (sqrDistance - sqrParentLength - sqrTargetLength) / (2f * lengths[0] * lengths[1]);
  31. if (angle0Cos >= -1f && angle0Cos <= 1f && angle1Cos >= -1f && angle1Cos <= 1f)
  32. {
  33. outAngles[0] = Mathf.Acos(angle0Cos) * Mathf.Rad2Deg;
  34. outAngles[1] = Mathf.Acos(angle1Cos) * Mathf.Rad2Deg;
  35. }
  36. return true;
  37. }
  38. }
  39. }