ConstraintPositionOffset.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.FinalIK {
  4. /// <summary>
  5. /// Offsets the transform from it's (animated) position.
  6. /// </summary>
  7. [System.Serializable]
  8. public class ConstraintPositionOffset : Constraint {
  9. #region Main Interface
  10. /// <summary>
  11. /// The position offset in world space.
  12. /// </summary>
  13. public Vector3 offset;
  14. public override void UpdateConstraint() {
  15. if (weight <= 0) return;
  16. if (!isValid) return;
  17. // Initiating
  18. if (!initiated) {
  19. // Storing default values
  20. defaultLocalPosition = transform.localPosition;
  21. lastLocalPosition = transform.localPosition;
  22. initiated = true;
  23. }
  24. // Check if position has changed. If true, set default local position to current.
  25. if (positionChanged) defaultLocalPosition = transform.localPosition;
  26. // Offsetting the position
  27. transform.localPosition = defaultLocalPosition;
  28. transform.position += offset * weight;
  29. // Store the current local position to check if it has changed in the next update.
  30. lastLocalPosition = transform.localPosition;
  31. }
  32. #endregion Main Interface
  33. public ConstraintPositionOffset() {}
  34. public ConstraintPositionOffset(Transform transform) {
  35. this.transform = transform;
  36. }
  37. private Vector3 defaultLocalPosition, lastLocalPosition;
  38. private bool initiated;
  39. /*
  40. * Check if position 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 positionChanged {
  44. get {
  45. return transform.localPosition != lastLocalPosition;
  46. }
  47. }
  48. }
  49. }