BoneFollower.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
  30. #define NEW_PREFAB_SYSTEM
  31. #endif
  32. using System;
  33. using UnityEngine;
  34. namespace Spine.Unity {
  35. /// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary>
  36. #if NEW_PREFAB_SYSTEM
  37. [ExecuteAlways]
  38. #else
  39. [ExecuteInEditMode]
  40. #endif
  41. [AddComponentMenu("Spine/BoneFollower")]
  42. [HelpURL("http://esotericsoftware.com/spine-unity#BoneFollower")]
  43. public class BoneFollower : MonoBehaviour {
  44. #region Inspector
  45. public SkeletonRenderer skeletonRenderer;
  46. public SkeletonRenderer SkeletonRenderer {
  47. get { return skeletonRenderer; }
  48. set {
  49. skeletonRenderer = value;
  50. Initialize();
  51. }
  52. }
  53. /// <summary>If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly.</summary>
  54. [SpineBone(dataField: "skeletonRenderer")]
  55. public string boneName;
  56. public bool followXYPosition = true;
  57. public bool followZPosition = true;
  58. public bool followBoneRotation = true;
  59. [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")]
  60. public bool followSkeletonFlip = true;
  61. [Tooltip("Follows the target bone's local scale.")]
  62. [UnityEngine.Serialization.FormerlySerializedAs("followScale")]
  63. public bool followLocalScale = false;
  64. [Tooltip("Includes the parent bone's lossy world scale. BoneFollower cannot inherit rotated/skewed scale because of UnityEngine.Transform property limitations.")]
  65. public bool followParentWorldScale = false;
  66. public enum AxisOrientation {
  67. XAxis = 1,
  68. YAxis
  69. }
  70. [Tooltip("Applies when 'Follow Skeleton Flip' is disabled but 'Follow Bone Rotation' is enabled."
  71. + " When flipping the skeleton by scaling its Transform, this follower's rotation is adjusted"
  72. + " instead of its scale to follow the bone orientation. When one of the axes is flipped, "
  73. + " only one axis can be followed, either the X or the Y axis, which is selected here.")]
  74. public AxisOrientation maintainedAxisOrientation = AxisOrientation.XAxis;
  75. [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")]
  76. public bool initializeOnAwake = true;
  77. #endregion
  78. [NonSerialized] public bool valid;
  79. [NonSerialized] public Bone bone;
  80. Transform skeletonTransform;
  81. bool skeletonTransformIsParent;
  82. /// <summary>
  83. /// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly.</summary>
  84. public bool SetBone (string name) {
  85. bone = skeletonRenderer.skeleton.FindBone(name);
  86. if (bone == null) {
  87. Debug.LogError("Bone not found: " + name, this);
  88. return false;
  89. }
  90. boneName = name;
  91. return true;
  92. }
  93. public void Awake () {
  94. if (initializeOnAwake) Initialize();
  95. }
  96. public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) {
  97. Initialize();
  98. }
  99. public void Initialize () {
  100. bone = null;
  101. valid = skeletonRenderer != null && skeletonRenderer.valid;
  102. if (!valid) return;
  103. skeletonTransform = skeletonRenderer.transform;
  104. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  105. skeletonRenderer.OnRebuild += HandleRebuildRenderer;
  106. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  107. if (!string.IsNullOrEmpty(boneName))
  108. bone = skeletonRenderer.skeleton.FindBone(boneName);
  109. #if UNITY_EDITOR
  110. if (Application.isEditor)
  111. LateUpdate();
  112. #endif
  113. }
  114. void OnDestroy () {
  115. if (skeletonRenderer != null)
  116. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  117. }
  118. public void LateUpdate () {
  119. if (!valid) {
  120. Initialize();
  121. return;
  122. }
  123. #if UNITY_EDITOR
  124. if (!Application.isPlaying)
  125. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  126. #endif
  127. if (bone == null) {
  128. if (string.IsNullOrEmpty(boneName)) return;
  129. bone = skeletonRenderer.skeleton.FindBone(boneName);
  130. if (!SetBone(boneName)) return;
  131. }
  132. Transform thisTransform = this.transform;
  133. float additionalFlipScale = 1;
  134. if (skeletonTransformIsParent) {
  135. // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent
  136. thisTransform.localPosition = new Vector3(followXYPosition ? bone.WorldX : thisTransform.localPosition.x,
  137. followXYPosition ? bone.WorldY : thisTransform.localPosition.y,
  138. followZPosition ? 0f : thisTransform.localPosition.z);
  139. if (followBoneRotation) {
  140. float halfRotation = Mathf.Atan2(bone.C, bone.A) * 0.5f;
  141. if (followLocalScale && bone.ScaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation.
  142. halfRotation += Mathf.PI * 0.5f;
  143. var q = default(Quaternion);
  144. q.z = Mathf.Sin(halfRotation);
  145. q.w = Mathf.Cos(halfRotation);
  146. thisTransform.localRotation = q;
  147. }
  148. } else {
  149. // For special cases: Use transform world properties if transform relationship is complicated
  150. Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.WorldX, bone.WorldY, 0f));
  151. if (!followZPosition) targetWorldPosition.z = thisTransform.position.z;
  152. if (!followXYPosition) {
  153. targetWorldPosition.x = thisTransform.position.x;
  154. targetWorldPosition.y = thisTransform.position.y;
  155. }
  156. Vector3 skeletonLossyScale = skeletonTransform.lossyScale;
  157. Transform transformParent = thisTransform.parent;
  158. Vector3 parentLossyScale = transformParent != null ? transformParent.lossyScale : Vector3.one;
  159. if (followBoneRotation) {
  160. float boneWorldRotation = bone.WorldRotationX;
  161. if ((skeletonLossyScale.x * skeletonLossyScale.y) < 0)
  162. boneWorldRotation = -boneWorldRotation;
  163. if (followSkeletonFlip || maintainedAxisOrientation == AxisOrientation.XAxis) {
  164. if ((skeletonLossyScale.x * parentLossyScale.x < 0))
  165. boneWorldRotation += 180f;
  166. } else {
  167. if ((skeletonLossyScale.y * parentLossyScale.y < 0))
  168. boneWorldRotation += 180f;
  169. }
  170. Vector3 worldRotation = skeletonTransform.rotation.eulerAngles;
  171. if (followLocalScale && bone.ScaleX < 0) boneWorldRotation += 180f;
  172. thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation));
  173. } else {
  174. thisTransform.position = targetWorldPosition;
  175. }
  176. additionalFlipScale = Mathf.Sign(skeletonLossyScale.x * parentLossyScale.x
  177. * skeletonLossyScale.y * parentLossyScale.y);
  178. }
  179. Bone parentBone = bone.Parent;
  180. Vector3 localScale = new Vector3(1f, 1f, 1f);
  181. if (followParentWorldScale && parentBone != null)
  182. localScale = new Vector3(parentBone.WorldScaleX, parentBone.WorldScaleY, 1f);
  183. if (followLocalScale)
  184. localScale.Scale(new Vector3(bone.ScaleX, bone.ScaleY, 1f));
  185. if (followSkeletonFlip)
  186. localScale.y *= Mathf.Sign(bone.Skeleton.ScaleX * bone.Skeleton.ScaleY) * additionalFlipScale;
  187. thisTransform.localScale = localScale;
  188. }
  189. }
  190. }