BoneFollower.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. public class BoneFollower : MonoBehaviour {
  43. #region Inspector
  44. public SkeletonRenderer skeletonRenderer;
  45. public SkeletonRenderer SkeletonRenderer {
  46. get { return skeletonRenderer; }
  47. set {
  48. skeletonRenderer = value;
  49. Initialize();
  50. }
  51. }
  52. /// <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>
  53. [SpineBone(dataField: "skeletonRenderer")]
  54. [SerializeField] public string boneName;
  55. public bool followXYPosition = true;
  56. public bool followZPosition = true;
  57. public bool followBoneRotation = true;
  58. [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")]
  59. public bool followSkeletonFlip = true;
  60. [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")]
  61. public bool followLocalScale = false;
  62. [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")]
  63. public bool initializeOnAwake = true;
  64. #endregion
  65. [NonSerialized] public bool valid;
  66. [NonSerialized] public Bone bone;
  67. Transform skeletonTransform;
  68. bool skeletonTransformIsParent;
  69. /// <summary>
  70. /// 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>
  71. public bool SetBone (string name) {
  72. bone = skeletonRenderer.skeleton.FindBone(name);
  73. if (bone == null) {
  74. Debug.LogError("Bone not found: " + name, this);
  75. return false;
  76. }
  77. boneName = name;
  78. return true;
  79. }
  80. public void Awake () {
  81. if (initializeOnAwake) Initialize();
  82. }
  83. public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) {
  84. Initialize();
  85. }
  86. public void Initialize () {
  87. bone = null;
  88. valid = skeletonRenderer != null && skeletonRenderer.valid;
  89. if (!valid) return;
  90. skeletonTransform = skeletonRenderer.transform;
  91. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  92. skeletonRenderer.OnRebuild += HandleRebuildRenderer;
  93. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  94. if (!string.IsNullOrEmpty(boneName))
  95. bone = skeletonRenderer.skeleton.FindBone(boneName);
  96. #if UNITY_EDITOR
  97. if (Application.isEditor)
  98. LateUpdate();
  99. #endif
  100. }
  101. void OnDestroy () {
  102. if (skeletonRenderer != null)
  103. skeletonRenderer.OnRebuild -= HandleRebuildRenderer;
  104. }
  105. public void LateUpdate () {
  106. if (!valid) {
  107. Initialize();
  108. return;
  109. }
  110. #if UNITY_EDITOR
  111. if (!Application.isPlaying)
  112. skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent);
  113. #endif
  114. if (bone == null) {
  115. if (string.IsNullOrEmpty(boneName)) return;
  116. bone = skeletonRenderer.skeleton.FindBone(boneName);
  117. if (!SetBone(boneName)) return;
  118. }
  119. Transform thisTransform = this.transform;
  120. if (skeletonTransformIsParent) {
  121. // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent
  122. thisTransform.localPosition = new Vector3(followXYPosition ? bone.worldX : thisTransform.localPosition.x,
  123. followXYPosition ? bone.worldY : thisTransform.localPosition.y,
  124. followZPosition ? 0f : thisTransform.localPosition.z);
  125. if (followBoneRotation) {
  126. float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f;
  127. if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation.
  128. halfRotation += Mathf.PI * 0.5f;
  129. var q = default(Quaternion);
  130. q.z = Mathf.Sin(halfRotation);
  131. q.w = Mathf.Cos(halfRotation);
  132. thisTransform.localRotation = q;
  133. }
  134. } else {
  135. // For special cases: Use transform world properties if transform relationship is complicated
  136. Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f));
  137. if (!followZPosition) targetWorldPosition.z = thisTransform.position.z;
  138. if (!followXYPosition) {
  139. targetWorldPosition.x = thisTransform.position.x;
  140. targetWorldPosition.y = thisTransform.position.y;
  141. }
  142. float boneWorldRotation = bone.WorldRotationX;
  143. Transform transformParent = thisTransform.parent;
  144. if (transformParent != null) {
  145. Matrix4x4 m = transformParent.localToWorldMatrix;
  146. if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative
  147. boneWorldRotation = -boneWorldRotation;
  148. }
  149. if (followBoneRotation) {
  150. Vector3 worldRotation = skeletonTransform.rotation.eulerAngles;
  151. if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f;
  152. thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation));
  153. } else {
  154. thisTransform.position = targetWorldPosition;
  155. }
  156. }
  157. Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f);
  158. if (followSkeletonFlip) localScale.y *= Mathf.Sign(bone.skeleton.ScaleX * bone.skeleton.ScaleY);
  159. thisTransform.localScale = localScale;
  160. }
  161. }
  162. }