FBBIKArmBending.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using UnityEngine;
  2. using System.Collections;
  3. using RootMotion.FinalIK;
  4. namespace RootMotion.FinalIK {
  5. /// <summary>
  6. /// Calculates bending direction and hand rotations for a FBBIK rig for VR hand controllers.
  7. /// </summary>
  8. public class FBBIKArmBending : MonoBehaviour {
  9. public FullBodyBipedIK ik;
  10. // Bend direction offset for the arms
  11. public Vector3 bendDirectionOffsetLeft;
  12. public Vector3 bendDirectionOffsetRight;
  13. // Add some bend direction offset in character space
  14. public Vector3 characterSpaceBendOffsetLeft;
  15. public Vector3 characterSpaceBendOffsetRight;
  16. private Quaternion leftHandTargetRotation;
  17. private Quaternion rightHandTargetRotation;
  18. private bool initiated;
  19. void LateUpdate() {
  20. if (ik == null) return;
  21. if (!initiated) {
  22. ik.solver.OnPostUpdate += OnPostFBBIK;
  23. initiated = true;
  24. }
  25. // Left arm bend direction
  26. if (ik.solver.leftHandEffector.target != null) {
  27. Vector3 armAxisLeft = Vector3.left;
  28. ik.solver.leftArmChain.bendConstraint.direction = ik.solver.leftHandEffector.target.rotation * armAxisLeft + ik.solver.leftHandEffector.target.rotation * bendDirectionOffsetLeft + ik.transform.rotation * characterSpaceBendOffsetLeft;
  29. ik.solver.leftArmChain.bendConstraint.weight = 1f;
  30. }
  31. // Right arm bend direction
  32. if (ik.solver.rightHandEffector.target != null) {
  33. Vector3 armAxisRight = Vector3.right;
  34. ik.solver.rightArmChain.bendConstraint.direction = ik.solver.rightHandEffector.target.rotation * armAxisRight + ik.solver.rightHandEffector.target.rotation * bendDirectionOffsetRight + ik.transform.rotation * characterSpaceBendOffsetRight;
  35. ik.solver.rightArmChain.bendConstraint.weight = 1f;
  36. }
  37. }
  38. void OnPostFBBIK() {
  39. if (ik == null) return;
  40. // Rotate hand bones
  41. if (ik.solver.leftHandEffector.target != null) {
  42. ik.references.leftHand.rotation = ik.solver.leftHandEffector.target.rotation;
  43. }
  44. if (ik.solver.rightHandEffector.target != null) {
  45. ik.references.rightHand.rotation = ik.solver.rightHandEffector.target.rotation;
  46. }
  47. }
  48. void OnDestroy() {
  49. if (ik != null) ik.solver.OnPostUpdate -= OnPostFBBIK;
  50. }
  51. }
  52. }