SkeletonRootMotionBase.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. using Spine.Unity.AnimationTools;
  30. using System;
  31. using System.Collections.Generic;
  32. using UnityEngine;
  33. namespace Spine.Unity {
  34. /// <summary>
  35. /// Base class for skeleton root motion components.
  36. /// </summary>
  37. abstract public class SkeletonRootMotionBase : MonoBehaviour {
  38. #region Inspector
  39. [SpineBone]
  40. [SerializeField]
  41. protected string rootMotionBoneName = "root";
  42. public bool transformPositionX = true;
  43. public bool transformPositionY = true;
  44. public float rootMotionScaleX = 1;
  45. public float rootMotionScaleY = 1;
  46. /// <summary>Skeleton space X translation per skeleton space Y translation root motion.</summary>
  47. public float rootMotionTranslateXPerY = 0;
  48. /// <summary>Skeleton space Y translation per skeleton space X translation root motion.</summary>
  49. public float rootMotionTranslateYPerX = 0;
  50. [Header("Optional")]
  51. public Rigidbody2D rigidBody2D;
  52. public bool applyRigidbody2DGravity = false;
  53. public Rigidbody rigidBody;
  54. public bool UsesRigidbody {
  55. get { return rigidBody != null || rigidBody2D != null; }
  56. }
  57. #endregion
  58. protected ISkeletonComponent skeletonComponent;
  59. protected Bone rootMotionBone;
  60. protected int rootMotionBoneIndex;
  61. protected List<Bone> topLevelBones = new List<Bone>();
  62. protected Vector2 initialOffset = Vector2.zero;
  63. protected Vector2 tempSkeletonDisplacement;
  64. protected Vector2 rigidbodyDisplacement;
  65. protected virtual void Reset () {
  66. FindRigidbodyComponent();
  67. }
  68. protected virtual void Start () {
  69. skeletonComponent = GetComponent<ISkeletonComponent>();
  70. GatherTopLevelBones();
  71. SetRootMotionBone(rootMotionBoneName);
  72. if (rootMotionBone != null)
  73. initialOffset = new Vector2(rootMotionBone.X, rootMotionBone.Y);
  74. var skeletonAnimation = skeletonComponent as ISkeletonAnimation;
  75. if (skeletonAnimation != null) {
  76. skeletonAnimation.UpdateLocal -= HandleUpdateLocal;
  77. skeletonAnimation.UpdateLocal += HandleUpdateLocal;
  78. }
  79. }
  80. protected virtual void FixedUpdate () {
  81. if (!this.isActiveAndEnabled)
  82. return; // Root motion is only applied when component is enabled.
  83. if (rigidBody2D != null) {
  84. Vector2 gravityAndVelocityMovement = Vector2.zero;
  85. if (applyRigidbody2DGravity) {
  86. float deltaTime = Time.fixedDeltaTime;
  87. float deltaTimeSquared = (deltaTime * deltaTime);
  88. rigidBody2D.velocity += rigidBody2D.gravityScale * Physics2D.gravity * deltaTime;
  89. gravityAndVelocityMovement = 0.5f * rigidBody2D.gravityScale * Physics2D.gravity * deltaTimeSquared +
  90. rigidBody2D.velocity * deltaTime;
  91. }
  92. rigidBody2D.MovePosition(gravityAndVelocityMovement + new Vector2(transform.position.x, transform.position.y)
  93. + rigidbodyDisplacement);
  94. }
  95. if (rigidBody != null) {
  96. rigidBody.MovePosition(transform.position
  97. + new Vector3(rigidbodyDisplacement.x, rigidbodyDisplacement.y, 0));
  98. }
  99. Vector2 parentBoneScale;
  100. GetScaleAffectingRootMotion(out parentBoneScale);
  101. ClearEffectiveBoneOffsets(parentBoneScale);
  102. rigidbodyDisplacement = Vector2.zero;
  103. tempSkeletonDisplacement = Vector2.zero;
  104. }
  105. protected virtual void OnDisable () {
  106. rigidbodyDisplacement = Vector2.zero;
  107. tempSkeletonDisplacement = Vector2.zero;
  108. }
  109. protected void FindRigidbodyComponent () {
  110. rigidBody2D = this.GetComponent<Rigidbody2D>();
  111. if (!rigidBody2D)
  112. rigidBody = this.GetComponent<Rigidbody>();
  113. if (!rigidBody2D && !rigidBody) {
  114. rigidBody2D = this.GetComponentInParent<Rigidbody2D>();
  115. if (!rigidBody2D)
  116. rigidBody = this.GetComponentInParent<Rigidbody>();
  117. }
  118. }
  119. protected virtual float AdditionalScale { get { return 1.0f; } }
  120. abstract protected Vector2 CalculateAnimationsMovementDelta ();
  121. abstract public Vector2 GetRemainingRootMotion (int trackIndex = 0);
  122. public struct RootMotionInfo {
  123. public Vector2 start;
  124. public Vector2 current;
  125. public Vector2 mid;
  126. public Vector2 end;
  127. public bool timeIsPastMid;
  128. };
  129. abstract public RootMotionInfo GetRootMotionInfo (int trackIndex = 0);
  130. public void SetRootMotionBone (string name) {
  131. var skeleton = skeletonComponent.Skeleton;
  132. Bone bone = skeleton.FindBone(name);
  133. if (bone != null) {
  134. this.rootMotionBoneIndex = bone.Data.Index;
  135. this.rootMotionBone = bone;
  136. } else {
  137. Debug.Log("Bone named \"" + name + "\" could not be found.");
  138. this.rootMotionBoneIndex = 0;
  139. this.rootMotionBone = skeleton.RootBone;
  140. }
  141. }
  142. public void AdjustRootMotionToDistance (Vector2 distanceToTarget, int trackIndex = 0, bool adjustX = true, bool adjustY = true,
  143. float minX = 0, float maxX = float.MaxValue, float minY = 0, float maxY = float.MaxValue,
  144. bool allowXTranslation = false, bool allowYTranslation = false) {
  145. Vector2 distanceToTargetSkeletonSpace = (Vector2)transform.InverseTransformVector(distanceToTarget);
  146. Vector2 scaleAffectingRootMotion = GetScaleAffectingRootMotion();
  147. if (UsesRigidbody)
  148. distanceToTargetSkeletonSpace -= tempSkeletonDisplacement;
  149. Vector2 remainingRootMotionSkeletonSpace = GetRemainingRootMotion(trackIndex);
  150. remainingRootMotionSkeletonSpace.Scale(scaleAffectingRootMotion);
  151. if (remainingRootMotionSkeletonSpace.x == 0)
  152. remainingRootMotionSkeletonSpace.x = 0.0001f;
  153. if (remainingRootMotionSkeletonSpace.y == 0)
  154. remainingRootMotionSkeletonSpace.y = 0.0001f;
  155. if (adjustX)
  156. rootMotionScaleX = Math.Min(maxX, Math.Max(minX, distanceToTargetSkeletonSpace.x / remainingRootMotionSkeletonSpace.x));
  157. if (adjustY)
  158. rootMotionScaleY = Math.Min(maxY, Math.Max(minY, distanceToTargetSkeletonSpace.y / remainingRootMotionSkeletonSpace.y));
  159. if (allowXTranslation)
  160. rootMotionTranslateXPerY = (distanceToTargetSkeletonSpace.x - remainingRootMotionSkeletonSpace.x * rootMotionScaleX) / remainingRootMotionSkeletonSpace.y;
  161. if (allowYTranslation)
  162. rootMotionTranslateYPerX = (distanceToTargetSkeletonSpace.y - remainingRootMotionSkeletonSpace.y * rootMotionScaleY) / remainingRootMotionSkeletonSpace.x;
  163. }
  164. public Vector2 GetAnimationRootMotion (Animation animation) {
  165. return GetAnimationRootMotion(0, animation.Duration, animation);
  166. }
  167. public Vector2 GetAnimationRootMotion (float startTime, float endTime,
  168. Animation animation) {
  169. TranslateTimeline timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex);
  170. if (timeline != null) {
  171. return GetTimelineMovementDelta(startTime, endTime, timeline, animation);
  172. }
  173. TranslateXTimeline xTimeline = animation.FindTimelineForBone<TranslateXTimeline>(rootMotionBoneIndex);
  174. TranslateYTimeline yTimeline = animation.FindTimelineForBone<TranslateYTimeline>(rootMotionBoneIndex);
  175. if (xTimeline != null || yTimeline != null) {
  176. return GetTimelineMovementDelta(startTime, endTime, xTimeline, yTimeline, animation);
  177. }
  178. return Vector2.zero;
  179. }
  180. public RootMotionInfo GetAnimationRootMotionInfo (Animation animation, float currentTime) {
  181. RootMotionInfo rootMotion = new RootMotionInfo();
  182. float duration = animation.Duration;
  183. float mid = duration * 0.5f;
  184. rootMotion.timeIsPastMid = currentTime > mid;
  185. TranslateTimeline timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex);
  186. if (timeline != null) {
  187. rootMotion.start = timeline.Evaluate(0);
  188. rootMotion.current = timeline.Evaluate(currentTime);
  189. rootMotion.mid = timeline.Evaluate(mid);
  190. rootMotion.end = timeline.Evaluate(duration);
  191. return rootMotion;
  192. }
  193. TranslateXTimeline xTimeline = animation.FindTimelineForBone<TranslateXTimeline>(rootMotionBoneIndex);
  194. TranslateYTimeline yTimeline = animation.FindTimelineForBone<TranslateYTimeline>(rootMotionBoneIndex);
  195. if (xTimeline != null || yTimeline != null) {
  196. rootMotion.start = TimelineExtensions.Evaluate(xTimeline, yTimeline, 0);
  197. rootMotion.current = TimelineExtensions.Evaluate(xTimeline, yTimeline, currentTime);
  198. rootMotion.mid = TimelineExtensions.Evaluate(xTimeline, yTimeline, mid);
  199. rootMotion.end = TimelineExtensions.Evaluate(xTimeline, yTimeline, duration);
  200. return rootMotion;
  201. }
  202. return rootMotion;
  203. }
  204. Vector2 GetTimelineMovementDelta (float startTime, float endTime,
  205. TranslateTimeline timeline, Animation animation) {
  206. Vector2 currentDelta;
  207. if (startTime > endTime) // Looped
  208. currentDelta = (timeline.Evaluate(animation.Duration) - timeline.Evaluate(startTime))
  209. + (timeline.Evaluate(endTime) - timeline.Evaluate(0));
  210. else if (startTime != endTime) // Non-looped
  211. currentDelta = timeline.Evaluate(endTime) - timeline.Evaluate(startTime);
  212. else
  213. currentDelta = Vector2.zero;
  214. return currentDelta;
  215. }
  216. Vector2 GetTimelineMovementDelta (float startTime, float endTime,
  217. TranslateXTimeline xTimeline, TranslateYTimeline yTimeline, Animation animation) {
  218. Vector2 currentDelta;
  219. if (startTime > endTime) // Looped
  220. currentDelta =
  221. (TimelineExtensions.Evaluate(xTimeline, yTimeline, animation.Duration)
  222. - TimelineExtensions.Evaluate(xTimeline, yTimeline, startTime))
  223. + (TimelineExtensions.Evaluate(xTimeline, yTimeline, endTime)
  224. - TimelineExtensions.Evaluate(xTimeline, yTimeline, 0));
  225. else if (startTime != endTime) // Non-looped
  226. currentDelta = TimelineExtensions.Evaluate(xTimeline, yTimeline, endTime)
  227. - TimelineExtensions.Evaluate(xTimeline, yTimeline, startTime);
  228. else
  229. currentDelta = Vector2.zero;
  230. return currentDelta;
  231. }
  232. void GatherTopLevelBones () {
  233. topLevelBones.Clear();
  234. var skeleton = skeletonComponent.Skeleton;
  235. foreach (var bone in skeleton.Bones) {
  236. if (bone.Parent == null)
  237. topLevelBones.Add(bone);
  238. }
  239. }
  240. void HandleUpdateLocal (ISkeletonAnimation animatedSkeletonComponent) {
  241. if (!this.isActiveAndEnabled)
  242. return; // Root motion is only applied when component is enabled.
  243. var boneLocalDelta = CalculateAnimationsMovementDelta();
  244. Vector2 parentBoneScale;
  245. Vector2 skeletonDelta = GetSkeletonSpaceMovementDelta(boneLocalDelta, out parentBoneScale);
  246. ApplyRootMotion(skeletonDelta, parentBoneScale);
  247. }
  248. void ApplyRootMotion (Vector2 skeletonDelta, Vector2 parentBoneScale) {
  249. // Apply root motion to Transform or RigidBody;
  250. if (UsesRigidbody) {
  251. rigidbodyDisplacement += (Vector2)transform.TransformVector(skeletonDelta);
  252. // Accumulated displacement is applied on the next Physics update in FixedUpdate.
  253. // Until the next Physics update, tempBoneDisplacement is offsetting bone locations
  254. // to prevent stutter which would otherwise occur if we don't move every Update.
  255. tempSkeletonDisplacement += skeletonDelta;
  256. SetEffectiveBoneOffsetsTo(tempSkeletonDisplacement, parentBoneScale);
  257. } else {
  258. transform.position += transform.TransformVector(skeletonDelta);
  259. ClearEffectiveBoneOffsets(parentBoneScale);
  260. }
  261. }
  262. Vector2 GetScaleAffectingRootMotion () {
  263. Vector2 parentBoneScale;
  264. return GetScaleAffectingRootMotion(out parentBoneScale);
  265. }
  266. Vector2 GetScaleAffectingRootMotion (out Vector2 parentBoneScale) {
  267. var skeleton = skeletonComponent.Skeleton;
  268. Vector2 totalScale = Vector2.one;
  269. totalScale.x *= skeleton.ScaleX;
  270. totalScale.y *= skeleton.ScaleY;
  271. parentBoneScale = Vector2.one;
  272. Bone scaleBone = rootMotionBone;
  273. while ((scaleBone = scaleBone.Parent) != null) {
  274. parentBoneScale.x *= scaleBone.ScaleX;
  275. parentBoneScale.y *= scaleBone.ScaleY;
  276. }
  277. totalScale = Vector2.Scale(totalScale, parentBoneScale);
  278. totalScale *= AdditionalScale;
  279. return totalScale;
  280. }
  281. Vector2 GetSkeletonSpaceMovementDelta (Vector2 boneLocalDelta, out Vector2 parentBoneScale) {
  282. Vector2 skeletonDelta = boneLocalDelta;
  283. Vector2 totalScale = GetScaleAffectingRootMotion(out parentBoneScale);
  284. skeletonDelta.Scale(totalScale);
  285. Vector2 rootMotionTranslation = new Vector2(
  286. rootMotionTranslateXPerY * skeletonDelta.y,
  287. rootMotionTranslateYPerX * skeletonDelta.x);
  288. skeletonDelta.x *= rootMotionScaleX;
  289. skeletonDelta.y *= rootMotionScaleY;
  290. skeletonDelta.x += rootMotionTranslation.x;
  291. skeletonDelta.y += rootMotionTranslation.y;
  292. if (!transformPositionX) skeletonDelta.x = 0f;
  293. if (!transformPositionY) skeletonDelta.y = 0f;
  294. return skeletonDelta;
  295. }
  296. void SetEffectiveBoneOffsetsTo (Vector2 displacementSkeletonSpace, Vector2 parentBoneScale) {
  297. // Move top level bones in opposite direction of the root motion bone
  298. var skeleton = skeletonComponent.Skeleton;
  299. foreach (var topLevelBone in topLevelBones) {
  300. if (topLevelBone == rootMotionBone) {
  301. if (transformPositionX) topLevelBone.X = displacementSkeletonSpace.x / skeleton.ScaleX;
  302. if (transformPositionY) topLevelBone.Y = displacementSkeletonSpace.y / skeleton.ScaleY;
  303. } else {
  304. float offsetX = (initialOffset.x - rootMotionBone.X) * parentBoneScale.x;
  305. float offsetY = (initialOffset.y - rootMotionBone.Y) * parentBoneScale.y;
  306. if (transformPositionX) topLevelBone.X = (displacementSkeletonSpace.x / skeleton.ScaleX) + offsetX;
  307. if (transformPositionY) topLevelBone.Y = (displacementSkeletonSpace.y / skeleton.ScaleY) + offsetY;
  308. }
  309. }
  310. }
  311. void ClearEffectiveBoneOffsets (Vector2 parentBoneScale) {
  312. SetEffectiveBoneOffsetsTo(Vector2.zero, parentBoneScale);
  313. }
  314. }
  315. }