CharacterMoveAction.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. using KairoEngine.Core;
  6. namespace KairoEngine.CharacterSystem
  7. {
  8. /// <summary>
  9. /// Action to move a character in a certain direction and speed.
  10. /// </summary>
  11. public class CharacterMoveAction : IAction
  12. {
  13. CharacterController character; // Reference to the character that will move
  14. Vector2 direction;
  15. Vector2 lookDirection;
  16. bool done = false;
  17. float speed = 1f;
  18. // Constructor
  19. public CharacterMoveAction(CharacterController character, Vector2 direction, Vector2 lookDirection, float speed)
  20. {
  21. this.character = character;
  22. this.direction = direction;
  23. this.lookDirection = lookDirection;
  24. this.speed = speed;
  25. }
  26. public void Start()
  27. {
  28. UpdateLookDirection();
  29. GenericEvents.StartListening(character.unique_name + "-AnimationStepDone", End);
  30. character.animator.SetFloat("horizontal", (int)lookDirection.x);
  31. character.animator.SetFloat("vertical", (int)lookDirection.y);
  32. character.transform.Translate(new Vector3(direction.x * speed * Time.deltaTime, 0, direction.y * speed * Time.deltaTime));
  33. }
  34. public void Update()
  35. {
  36. UpdateLookDirection();
  37. character.animator.SetFloat("horizontal", (int)lookDirection.x);
  38. character.animator.SetFloat("vertical", (int)lookDirection.y);
  39. character.transform.Translate(new Vector3(direction.x * speed * Time.deltaTime, 0, direction.y * speed * Time.deltaTime));
  40. }
  41. public void End()
  42. {
  43. if(direction.x > 0.1f || direction.y > 0.1f || direction.x < -0.1f || direction.y < -0.1f) return;
  44. character.animator.SetFloat("horizontal", 0);
  45. character.animator.SetFloat("vertical", 0);
  46. GenericEvents.StopListening(character.unique_name + "-AnimationStepDone", End);
  47. done = true;
  48. }
  49. public bool IsDone()
  50. {
  51. return done;
  52. }
  53. public void UpdateLookDirection()
  54. {
  55. if(speed == 1.25f)
  56. {
  57. if(lookDirection.x > 0.1f) lookDirection.x = 1;
  58. else if(lookDirection.x < -0.1f) lookDirection.x = -1;
  59. else lookDirection.x = 0;
  60. if(lookDirection.y > 0.1f) lookDirection.y = 1;
  61. else if(lookDirection.y < -0.1f) lookDirection.y = -1;
  62. else lookDirection.y = 0;
  63. }
  64. else
  65. {
  66. if(lookDirection.x > 0.9f) lookDirection.x = 2;
  67. else if(lookDirection.x < -0.9f) lookDirection.x = -2;
  68. else lookDirection.x = 0;
  69. if(lookDirection.y > 0.9f) lookDirection.y = 2;
  70. else if(lookDirection.y < -0.9f) lookDirection.y = -2;
  71. else lookDirection.y = 0;
  72. }
  73. }
  74. }
  75. }