Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof(CapsuleCollider))]
  4. public class Stepper : MonoBehaviour
  5. {
  6.     #region Data
  7.     public LayerMask groundLayer;
  8.     public float collisionBuffer, stepHeight, slopeAngle;
  9.  
  10.     private CapsuleCollider capsule;
  11.     #endregion
  12.  
  13.     #region Unity Functions
  14.     private void Awake()
  15.     {
  16.         capsule = GetComponent<CapsuleCollider>();
  17.     }
  18.     private void FixedUpdate()
  19.     {
  20.         float groundDistance = -CalculateGroundDistance();
  21.  
  22.         // This also causes the transform to snap down the stairs too
  23.         // If you wanted to avoid this you would remove the Mathf.Abs and add a && groundDistance > 0.
  24.         if (Mathf.Abs(groundDistance) < stepHeight)
  25.             transform.position += new Vector3(0, groundDistance, 0);
  26.     }
  27.     #endregion
  28.  
  29.     #region Private Functions
  30.     private float CalculateGroundDistance()
  31.     {
  32.         // Calculating global scale.
  33.         float radius = (Mathf.Max(transform.lossyScale.x, transform.lossyScale.z) * capsule.radius) + collisionBuffer;
  34.         float height = capsule.height * transform.lossyScale.y;
  35.  
  36.         // Caluclating global position.
  37.         Vector3 castPosition = transform.TransformPoint(capsule.center) + new Vector3(0, radius, 0);
  38.  
  39.         if (Physics.SphereCast(castPosition, radius, Vector3.down, out RaycastHit hit, height, groundLayer)) {
  40.             hit.distance -= height / 2;
  41.         }
  42.  
  43.         float angle = Vector3.Angle(hit.normal, Vector3.up);
  44.         return angle > slopeAngle ? 0 : hit.distance;
  45.     }
  46.     #endregion
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement