SpineboyBeginnerModel.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using UnityEngine;
  2. using System.Collections;
  3. [SelectionBase]
  4. public class SpineboyBeginnerModel : MonoBehaviour {
  5. #region Inspector
  6. [Header("Current State")]
  7. public SpineBeginnerBodyState state;
  8. public bool facingLeft;
  9. [Range(-1f, 1f)]
  10. public float currentSpeed;
  11. [Header("Balance")]
  12. public float shootInterval = 0.12f;
  13. #endregion
  14. float lastShootTime;
  15. public event System.Action ShootEvent; // Lets other scripts know when Spineboy is shooting. Check C# Documentation to learn more about events and delegates.
  16. #region API
  17. public void TryJump () {
  18. StartCoroutine(JumpRoutine());
  19. }
  20. public void TryShoot () {
  21. float currentTime = Time.time;
  22. if (currentTime - lastShootTime > shootInterval) {
  23. lastShootTime = currentTime;
  24. if (ShootEvent != null) ShootEvent(); // Fire the "ShootEvent" event.
  25. }
  26. }
  27. public void TryMove (float speed) {
  28. currentSpeed = speed; // show the "speed" in the Inspector.
  29. if (speed != 0) {
  30. bool speedIsNegative = (speed < 0f);
  31. facingLeft = speedIsNegative; // Change facing direction whenever speed is not 0.
  32. }
  33. if (state != SpineBeginnerBodyState.Jumping) {
  34. state = (speed == 0) ? SpineBeginnerBodyState.Idle : SpineBeginnerBodyState.Running;
  35. }
  36. }
  37. #endregion
  38. IEnumerator JumpRoutine () {
  39. if (state == SpineBeginnerBodyState.Jumping) yield break; // Don't jump when already jumping.
  40. state = SpineBeginnerBodyState.Jumping;
  41. // Terribly-coded Fake jumping.
  42. {
  43. var pos = transform.localPosition;
  44. const float jumpTime = 1.2f;
  45. const float half = jumpTime * 0.5f;
  46. const float jumpPower = 20f;
  47. for (float t = 0; t < half; t += Time.deltaTime) {
  48. float d = jumpPower * (half - t);
  49. transform.Translate((d * Time.deltaTime) * Vector3.up);
  50. yield return null;
  51. }
  52. for (float t = 0; t < half; t += Time.deltaTime) {
  53. float d = jumpPower * t;
  54. transform.Translate((d * Time.deltaTime) * Vector3.down);
  55. yield return null;
  56. }
  57. transform.localPosition = pos;
  58. }
  59. state = SpineBeginnerBodyState.Idle;
  60. }
  61. }
  62. public enum SpineBeginnerBodyState {
  63. Idle,
  64. Running,
  65. Jumping
  66. }