Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Events;
- // Uses the collider to check directions to see if the object is currently on the ground, touching the wall, or touching the ceiling
- public class TouchingDirections : MonoBehaviour
- {
- public UnityEvent<bool> IsOnWallChanged;
- public ContactFilter2D castFilter;
- public float groundDistance = 0.05f;
- public float wallDistance = 0.2f;
- public float ceilingDistance = 0.05f;
- private CapsuleCollider2D touchingCol;
- private Animator animator;
- private RaycastHit2D[] groundHits = new RaycastHit2D[5];
- private RaycastHit2D[] wallHits = new RaycastHit2D[5];
- private RaycastHit2D[] ceilingHits = new RaycastHit2D[5];
- [SerializeField]
- private bool _isGrounded;
- public bool IsGrounded
- {
- get
- {
- return _isGrounded;
- }
- private set
- {
- _isGrounded = value;
- animator.SetBool(AnimationStrings.isGrounded, value);
- }
- }
- [SerializeField]
- private bool _isOnWall;
- public bool IsOnWall
- {
- get
- {
- return _isOnWall;
- }
- private set
- {
- if (value == _isOnWall)
- return;
- _isOnWall = value;
- animator.SetBool(AnimationStrings.isOnWall, value);
- IsOnWallChanged?.Invoke(_isOnWall);
- }
- }
- [SerializeField]
- private bool _isOnCeiling;
- private Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.right : Vector2.left;
- public bool IsOnCeiling
- {
- get
- {
- return _isOnCeiling;
- }
- private set
- {
- _isOnCeiling = value;
- animator.SetBool(AnimationStrings.isOnCeiling, value);
- }
- }
- private void Awake()
- {
- touchingCol = GetComponent<CapsuleCollider2D>();
- animator = GetComponent<Animator>();
- }
- private void FixedUpdate()
- {
- IsGrounded = touchingCol.Cast(Vector2.down, castFilter, groundHits, groundDistance) > 0;
- IsOnWall = touchingCol.Cast(wallCheckDirection, castFilter, wallHits, wallDistance) > 0;
- IsOnCeiling = touchingCol.Cast(Vector2.up, castFilter, ceilingHits, ceilingDistance) > 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment