SpineboyController.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using UnityEngine;
  2. using System.Collections;
  3. [RequireComponent(typeof(SkeletonAnimation), typeof(Rigidbody2D))]
  4. public class SpineboyController : MonoBehaviour {
  5. SkeletonAnimation skeletonAnimation;
  6. public string idleAnimation = "idle";
  7. public string walkAnimation = "walk";
  8. public string runAnimation = "run";
  9. public string hitAnimation = "hit";
  10. public string deathAnimation = "death";
  11. public float walkVelocity = 1;
  12. public float runVelocity = 3;
  13. public int hp = 10;
  14. string currentAnimation = "";
  15. bool hit = false;
  16. bool dead = false;
  17. void Start () {
  18. skeletonAnimation = GetComponent<SkeletonAnimation>();
  19. }
  20. void Update () {
  21. if (!dead) {
  22. float x = Input.GetAxis("Horizontal");
  23. float absX = Mathf.Abs(x);
  24. if (!hit) {
  25. if (x > 0)
  26. skeletonAnimation.skeleton.FlipX = false;
  27. else if (x < 0)
  28. skeletonAnimation.skeleton.FlipX = true;
  29. if (absX > 0.7f) {
  30. SetAnimation(runAnimation, true);
  31. rigidbody2D.velocity = new Vector2(runVelocity * Mathf.Sign(x), rigidbody2D.velocity.y);
  32. } else if (absX > 0) {
  33. SetAnimation(walkAnimation, true);
  34. rigidbody2D.velocity = new Vector2(walkVelocity * Mathf.Sign(x), rigidbody2D.velocity.y);
  35. } else {
  36. SetAnimation(idleAnimation, true);
  37. rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
  38. }
  39. } else {
  40. if (skeletonAnimation.state.GetCurrent(0).Animation.Name != hitAnimation)
  41. hit = false;
  42. }
  43. }
  44. }
  45. void SetAnimation (string anim, bool loop) {
  46. if (currentAnimation != anim) {
  47. skeletonAnimation.state.SetAnimation(0, anim, loop);
  48. currentAnimation = anim;
  49. }
  50. }
  51. void OnMouseUp () {
  52. if (hp > 0) {
  53. hp--;
  54. if (hp == 0) {
  55. SetAnimation(deathAnimation, false);
  56. dead = true;
  57. } else {
  58. skeletonAnimation.state.SetAnimation(0, hitAnimation, false);
  59. skeletonAnimation.state.AddAnimation(0, currentAnimation, true, 0);
  60. rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
  61. hit = true;
  62. }
  63. }
  64. }
  65. }