Jumper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using UI;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using Game;
  6. namespace Player
  7. {
  8. [RequireComponent(typeof(Collider2D))]
  9. [RequireComponent(typeof(Rigidbody2D))]
  10. public class Jumper : MonoBehaviour
  11. {
  12. private const string TagGround = "Ground";
  13. private const string TagOrb = "Orb";
  14. private bool _grounded;
  15. private Orb _orb;
  16. private Rigidbody2D _rigidbody;
  17. private bool _buffering;
  18. private GameObject _lastCollidedGroundPiece = null;
  19. public event Action OnJump;
  20. private void Jump()
  21. {
  22. var modifier = Constants.JumpModifiersDictionary[_orb == null ? OrbType.Pink : _orb.Type];
  23. if (_orb != null)
  24. {
  25. if (_orb.Type is OrbType.Blue or OrbType.Green)
  26. _rigidbody.gravityScale = -_rigidbody.gravityScale;
  27. _orb.Deactivate();
  28. }
  29. var velocity = _rigidbody.velocity;
  30. velocity.y = 0;
  31. _rigidbody.velocity = velocity;
  32. var force = Constants.CalculateJumpForce(modifier, _rigidbody.gravityScale);
  33. _rigidbody.AddForce(force, ForceMode2D.Impulse);
  34. OnJump?.Invoke();
  35. }
  36. private void OnPointerJustDown(PointerEventData eventData)
  37. {
  38. if (_grounded || _orb != null)
  39. Jump();
  40. else
  41. _buffering = true;
  42. }
  43. private void StopBuffering(PointerEventData eventData) => _buffering = false;
  44. private void Awake()
  45. {
  46. _rigidbody = GetComponent<Rigidbody2D>();
  47. TouchCatcher.PointerJustDown += OnPointerJustDown;
  48. TouchCatcher.PointerUp += StopBuffering;
  49. }
  50. private void OnCollisionEnter2D(Collision2D other)
  51. {
  52. if (other.gameObject.CompareTag(TagGround))
  53. {
  54. _grounded = true;
  55. _lastCollidedGroundPiece = other.gameObject;
  56. if (TouchCatcher.IsPointerDown) Jump();
  57. }
  58. }
  59. private void OnCollisionExit2D(Collision2D other)
  60. {
  61. if (other.gameObject.CompareTag(TagGround) && _lastCollidedGroundPiece == other.gameObject)
  62. _grounded = false;
  63. }
  64. private void OnTriggerEnter2D(Collider2D other)
  65. {
  66. if (other.CompareTag(TagOrb))
  67. {
  68. _orb = other.GetComponent<Orb>();
  69. if (_buffering) Jump();
  70. }
  71. }
  72. private void OnTriggerExit2D(Collider2D other)
  73. {
  74. if (other.CompareTag(TagOrb) && other.GetComponent<Orb>() == _orb)
  75. _orb = null;
  76. }
  77. private void OnDestroy()
  78. {
  79. TouchCatcher.PointerJustDown -= OnPointerJustDown;
  80. TouchCatcher.PointerUp -= StopBuffering;
  81. }
  82. }
  83. }