SkeletonAnimation.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 UnityEngine;
  33. namespace Spine.Unity {
  34. #if NEW_PREFAB_SYSTEM
  35. [ExecuteAlways]
  36. #else
  37. [ExecuteInEditMode]
  38. #endif
  39. [AddComponentMenu("Spine/SkeletonAnimation")]
  40. public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent {
  41. #region IAnimationStateComponent
  42. /// <summary>
  43. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  44. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  45. public Spine.AnimationState state;
  46. /// <summary>
  47. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  48. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  49. public Spine.AnimationState AnimationState { get { return this.state; } }
  50. private bool wasUpdatedAfterInit = true;
  51. #endregion
  52. #region Bone Callbacks ISkeletonAnimation
  53. protected event UpdateBonesDelegate _UpdateLocal;
  54. protected event UpdateBonesDelegate _UpdateWorld;
  55. protected event UpdateBonesDelegate _UpdateComplete;
  56. /// <summary>
  57. /// Occurs after the animations are applied and before world space values are resolved.
  58. /// Use this callback when you want to set bone local values.
  59. /// </summary>
  60. public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
  61. /// <summary>
  62. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  63. /// Using this callback will cause the world space values to be solved an extra time.
  64. /// Use this callback if want to use bone world space values, and also set bone local values.</summary>
  65. public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
  66. /// <summary>
  67. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  68. /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
  69. /// This callback can also be used when setting world position and the bone matrix.</summary>
  70. public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
  71. #endregion
  72. #region Serialized state and Beginner API
  73. [SerializeField]
  74. [SpineAnimation]
  75. private string _animationName;
  76. /// <summary>
  77. /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized.
  78. /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary>
  79. public string AnimationName {
  80. get {
  81. if (!valid) {
  82. return _animationName;
  83. } else {
  84. TrackEntry entry = state.GetCurrent(0);
  85. return entry == null ? null : entry.Animation.Name;
  86. }
  87. }
  88. set {
  89. if (_animationName == value) {
  90. TrackEntry entry = state.GetCurrent(0);
  91. if (entry != null && entry.loop == loop)
  92. return;
  93. }
  94. _animationName = value;
  95. if (string.IsNullOrEmpty(value)) {
  96. state.ClearTrack(0);
  97. } else {
  98. var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(value);
  99. if (animationObject != null)
  100. state.SetAnimation(0, animationObject, loop);
  101. }
  102. }
  103. }
  104. /// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary>
  105. public bool loop;
  106. /// <summary>
  107. /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary>
  108. /// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks>
  109. public float timeScale = 1;
  110. #endregion
  111. #region Runtime Instantiation
  112. /// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary>
  113. /// <returns>The newly instantiated SkeletonAnimation</returns>
  114. public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) {
  115. return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset);
  116. }
  117. /// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary>
  118. /// <returns>The newly instantiated SkeletonAnimation component.</returns>
  119. public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset) {
  120. return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset);
  121. }
  122. #endregion
  123. /// <summary>
  124. /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary>
  125. public override void ClearState () {
  126. base.ClearState();
  127. if (state != null) state.ClearTracks();
  128. }
  129. /// <summary>
  130. /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary>
  131. /// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param>
  132. public override void Initialize (bool overwrite) {
  133. if (valid && !overwrite)
  134. return;
  135. base.Initialize(overwrite);
  136. if (!valid)
  137. return;
  138. state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
  139. wasUpdatedAfterInit = false;
  140. if (!string.IsNullOrEmpty(_animationName)) {
  141. var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName);
  142. if (animationObject != null) {
  143. state.SetAnimation(0, animationObject, loop);
  144. #if UNITY_EDITOR
  145. if (!Application.isPlaying)
  146. Update(0f);
  147. #endif
  148. }
  149. }
  150. }
  151. void Update () {
  152. #if UNITY_EDITOR
  153. if (!Application.isPlaying) {
  154. Update(0f);
  155. return;
  156. }
  157. #endif
  158. Update(Time.deltaTime);
  159. }
  160. /// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary>
  161. public void Update (float deltaTime) {
  162. if (!valid || state == null)
  163. return;
  164. deltaTime *= timeScale;
  165. skeleton.Update(deltaTime);
  166. state.Update(deltaTime);
  167. state.Apply(skeleton);
  168. if (_UpdateLocal != null)
  169. _UpdateLocal(this);
  170. skeleton.UpdateWorldTransform();
  171. if (_UpdateWorld != null) {
  172. _UpdateWorld(this);
  173. skeleton.UpdateWorldTransform();
  174. }
  175. if (_UpdateComplete != null) {
  176. _UpdateComplete(this);
  177. }
  178. wasUpdatedAfterInit = true;
  179. }
  180. public override void LateUpdate () {
  181. // instantiation can happen from Update() after this component, leading to a missing Update() call.
  182. if (!wasUpdatedAfterInit) Update(0);
  183. base.LateUpdate();
  184. }
  185. }
  186. }