ChrisTutorials

TouchingDirections.cs Final for Platformer Course

Aug 28th, 2024
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5.  
  6. // Uses the collider to check directions to see if the object is currently on the ground, touching the wall, or touching the ceiling
  7. public class TouchingDirections : MonoBehaviour
  8. {
  9. public UnityEvent<bool> IsOnWallChanged;
  10.  
  11. public ContactFilter2D castFilter;
  12. public float groundDistance = 0.05f;
  13. public float wallDistance = 0.2f;
  14. public float ceilingDistance = 0.05f;
  15.  
  16. private CapsuleCollider2D touchingCol;
  17. private Animator animator;
  18.  
  19. private RaycastHit2D[] groundHits = new RaycastHit2D[5];
  20. private RaycastHit2D[] wallHits = new RaycastHit2D[5];
  21. private RaycastHit2D[] ceilingHits = new RaycastHit2D[5];
  22.  
  23. [SerializeField]
  24. private bool _isGrounded;
  25.  
  26. public bool IsGrounded
  27. {
  28. get
  29. {
  30. return _isGrounded;
  31. }
  32. private set
  33. {
  34. _isGrounded = value;
  35. animator.SetBool(AnimationStrings.isGrounded, value);
  36. }
  37. }
  38.  
  39. [SerializeField]
  40. private bool _isOnWall;
  41.  
  42. public bool IsOnWall
  43. {
  44. get
  45. {
  46. return _isOnWall;
  47. }
  48. private set
  49. {
  50. if (value == _isOnWall)
  51. return;
  52.  
  53. _isOnWall = value;
  54. animator.SetBool(AnimationStrings.isOnWall, value);
  55. IsOnWallChanged?.Invoke(_isOnWall);
  56. }
  57. }
  58.  
  59. [SerializeField]
  60. private bool _isOnCeiling;
  61.  
  62. private Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.right : Vector2.left;
  63.  
  64. public bool IsOnCeiling
  65. {
  66. get
  67. {
  68. return _isOnCeiling;
  69. }
  70. private set
  71. {
  72. _isOnCeiling = value;
  73. animator.SetBool(AnimationStrings.isOnCeiling, value);
  74. }
  75. }
  76.  
  77. private void Awake()
  78. {
  79. touchingCol = GetComponent<CapsuleCollider2D>();
  80. animator = GetComponent<Animator>();
  81. }
  82.  
  83. private void FixedUpdate()
  84. {
  85. IsGrounded = touchingCol.Cast(Vector2.down, castFilter, groundHits, groundDistance) > 0;
  86. IsOnWall = touchingCol.Cast(wallCheckDirection, castFilter, wallHits, wallDistance) > 0;
  87. IsOnCeiling = touchingCol.Cast(Vector2.up, castFilter, ceilingHits, ceilingDistance) > 0;
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment