ConstraintRotationOffset.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.FinalIK {
  4. /// <summary>
  5. /// Offsets the transform from it's (animated) rotation
  6. /// </summary>
  7. [System.Serializable]
  8. public class ConstraintRotationOffset: Constraint {
  9. #region Main Interface
  10. /// <summary>
  11. /// The rotation offset in world space.
  12. /// </summary>
  13. public Quaternion offset;
  14. public override void UpdateConstraint() {
  15. if (weight <= 0) return;
  16. if (!isValid) return;
  17. // Initiating
  18. if (!initiated) {
  19. // Storing default rotations.
  20. defaultLocalRotation = transform.localRotation;
  21. lastLocalRotation = transform.localRotation;
  22. initiated = true;
  23. }
  24. // Check if rotation has changed. If true, set default local rotation to current.
  25. if (rotationChanged) defaultLocalRotation = transform.localRotation;
  26. // Offsetting the rotation
  27. transform.localRotation = defaultLocalRotation;
  28. transform.rotation = Quaternion.Slerp(transform.rotation, offset, weight);
  29. // Store the current local rotation to check if it has changed in the next update.
  30. lastLocalRotation = transform.localRotation;
  31. }
  32. #endregion Main Interface
  33. public ConstraintRotationOffset() {}
  34. public ConstraintRotationOffset(Transform transform) {
  35. this.transform = transform;
  36. }
  37. private Quaternion defaultRotation, defaultLocalRotation, lastLocalRotation, defaultTargetLocalRotation;
  38. private bool initiated;
  39. /*
  40. * Check if rotation has been changed by animation or any other external script.
  41. * If not, consider the object to be static and offset only from the default rotation.
  42. * */
  43. private bool rotationChanged {
  44. get {
  45. return transform.localRotation != lastLocalRotation;
  46. }
  47. }
  48. }
  49. }