BoneFollower.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")]
  62. public bool followLocalScale = false;
  63. public enum AxisOrientation {
  64. XAxis = 1,
  65. YAxis
  66. }
  67. [Tooltip("Applies when 'Follow Skeleton Flip' is disabled but 'Follow Bone Rotation' is enabled."
  68. + " When flipping the skeleton by scaling its Transform, this follower's rotation is adjusted"
  69. + " instead of its scale to follow the bone orientation. When one of the axes is flipped, "
  70. + " only one axis can be followed, either the X or the Y axis, which is selected here.")]
  71. public AxisOrientation maintainedAxisOrientation = AxisOrientation.XAxis;
  72. [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")]
  73. public bool initializeOnAwake = true;
  74. #endregion
  75. [NonSerialized] public bool valid;
  76. [NonSerialized] public Bone bone;
  77. Transform skeletonTransform;
  78. bool skeletonTransformIsParent;
  79. /// <summary>
  80. /// 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>
  81. public bool SetBone (string name) {
  82. bone = skeletonRenderer.skeleton.FindBone(name);
  83. if (bone == null) {
  84. Debug.LogError("Bone not found: " + name, this);
  85. return false;
  86. }
  87. boneName = name;
  88. return true;
  89. }
  90. public void Awake () {
  91. if (initializeOnAwake) Initialize();
  92. }
  93. public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) {
  94. Initialize();
  95. }
  96. public void Initialize () {
  97. bone = null;
  98. valid = skeletonRenderer != null && skeletonRenderer.valid;
  99. if (!valid) return;
  100. skeletonTransform = skeletonRenderer.transform;
  101. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  102. skeletonRenderer.OnRebuild += HandleRebuildRenderer;
  103. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  104. if (!string.IsNullOrEmpty(boneName))
  105. bone = skeletonRenderer.skeleton.FindBone(boneName);
  106. #if UNITY_EDITOR
  107. if (Application.isEditor)
  108. LateUpdate();
  109. #endif
  110. }
  111. void OnDestroy () {
  112. if (skeletonRenderer != null)
  113. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  114. }
  115. public void LateUpdate () {
  116. if (!valid) {
  117. Initialize();
  118. return;
  119. }
  120. #if UNITY_EDITOR
  121. if (!Application.isPlaying)
  122. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  123. #endif
  124. if (bone == null) {
  125. if (string.IsNullOrEmpty(boneName)) return;
  126. bone = skeletonRenderer.skeleton.FindBone(boneName);
  127. if (!SetBone(boneName)) return;
  128. }
  129. Transform thisTransform = this.transform;
  130. float additionalFlipScale = 1;
  131. if (skeletonTransformIsParent) {
  132. // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent
  133. thisTransform.localPosition = new Vector3(followXYPosition ? bone.worldX : thisTransform.localPosition.x,
  134. followXYPosition ? bone.worldY : thisTransform.localPosition.y,
  135. followZPosition ? 0f : thisTransform.localPosition.z);
  136. if (followBoneRotation) {
  137. float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f;
  138. if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation.
  139. halfRotation += Mathf.PI * 0.5f;
  140. var q = default(Quaternion);
  141. q.z = Mathf.Sin(halfRotation);
  142. q.w = Mathf.Cos(halfRotation);
  143. thisTransform.localRotation = q;
  144. }
  145. } else {
  146. // For special cases: Use transform world properties if transform relationship is complicated
  147. Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f));
  148. if (!followZPosition) targetWorldPosition.z = thisTransform.position.z;
  149. if (!followXYPosition) {
  150. targetWorldPosition.x = thisTransform.position.x;
  151. targetWorldPosition.y = thisTransform.position.y;
  152. }
  153. Vector3 skeletonLossyScale = skeletonTransform.lossyScale;
  154. Transform transformParent = thisTransform.parent;
  155. Vector3 parentLossyScale = transformParent != null ? transformParent.lossyScale : Vector3.one;
  156. if (followBoneRotation) {
  157. float boneWorldRotation = bone.WorldRotationX;
  158. if ((skeletonLossyScale.x * skeletonLossyScale.y) < 0)
  159. boneWorldRotation = -boneWorldRotation;
  160. if (followSkeletonFlip || maintainedAxisOrientation == AxisOrientation.XAxis) {
  161. if ((skeletonLossyScale.x * parentLossyScale.x < 0))
  162. boneWorldRotation += 180f;
  163. }
  164. else {
  165. if ((skeletonLossyScale.y * parentLossyScale.y < 0))
  166. boneWorldRotation += 180f;
  167. }
  168. Vector3 worldRotation = skeletonTransform.rotation.eulerAngles;
  169. if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f;
  170. thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation));
  171. } else {
  172. thisTransform.position = targetWorldPosition;
  173. }
  174. additionalFlipScale = Mathf.Sign(skeletonLossyScale.x * parentLossyScale.x
  175. * skeletonLossyScale.y * parentLossyScale.y);
  176. }
  177. Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f);
  178. if (followSkeletonFlip)
  179. localScale.y *= Mathf.Sign(bone.skeleton.ScaleX * bone.skeleton.ScaleY) * additionalFlipScale;
  180. thisTransform.localScale = localScale;
  181. }
  182. }
  183. }