AnimationStateWithMecanimExample.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Spine;
  5. using Spine.Unity;
  6. namespace Spine.Unity.Examples {
  7. public class AnimationStateWithMecanimExample : MonoBehaviour {
  8. SkeletonAnimation skeletonAnimation;
  9. Animator logicAnimator;
  10. [Header("Controls")]
  11. public KeyCode walkButton = KeyCode.LeftShift;
  12. public KeyCode jumpButton = KeyCode.Space;
  13. [Header("Animator Properties")]
  14. public string horizontalSpeedProperty = "Speed";
  15. public string verticalSpeedProperty = "VerticalSpeed";
  16. public string groundedProperty = "Grounded";
  17. [Header("Fake Physics")]
  18. public float jumpDuration = 1.5f;
  19. public Vector2 speed;
  20. public bool isGrounded;
  21. void Awake () {
  22. skeletonAnimation = GetComponent<SkeletonAnimation>();
  23. logicAnimator = GetComponent<Animator>();
  24. isGrounded = true;
  25. }
  26. void Update () {
  27. float x = Input.GetAxisRaw("Horizontal");
  28. if (Input.GetKey(walkButton)) {
  29. x *= 0.4f;
  30. }
  31. speed.x = x;
  32. // Flip skeleton.
  33. if (x != 0) {
  34. skeletonAnimation.Skeleton.ScaleX = x > 0 ? 1f : -1f;
  35. }
  36. if (Input.GetKeyDown(jumpButton)) {
  37. if (isGrounded)
  38. StartCoroutine(FakeJump());
  39. }
  40. logicAnimator.SetFloat(horizontalSpeedProperty, Mathf.Abs(speed.x));
  41. logicAnimator.SetFloat(verticalSpeedProperty, speed.y);
  42. logicAnimator.SetBool(groundedProperty, isGrounded);
  43. }
  44. IEnumerator FakeJump () {
  45. // Rise
  46. isGrounded = false;
  47. speed.y = 10f;
  48. float durationLeft = jumpDuration * 0.5f;
  49. while (durationLeft > 0) {
  50. durationLeft -= Time.deltaTime;
  51. if (!Input.GetKey(jumpButton)) break;
  52. yield return null;
  53. }
  54. // Fall
  55. speed.y = -10f;
  56. float fallDuration = (jumpDuration * 0.5f) - durationLeft;
  57. yield return new WaitForSeconds(fallDuration);
  58. // Land
  59. speed.y = 0f;
  60. isGrounded = true;
  61. yield return null;
  62. }
  63. }
  64. }