Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(CapsuleCollider))]
- public class Stepper : MonoBehaviour
- {
- #region Data
- public LayerMask groundLayer;
- public float collisionBuffer, stepHeight, slopeAngle;
- private CapsuleCollider capsule;
- #endregion
- #region Unity Functions
- private void Awake()
- {
- capsule = GetComponent<CapsuleCollider>();
- }
- private void FixedUpdate()
- {
- float groundDistance = -CalculateGroundDistance();
- // This also causes the transform to snap down the stairs too
- // If you wanted to avoid this you would remove the Mathf.Abs and add a && groundDistance > 0.
- if (Mathf.Abs(groundDistance) < stepHeight)
- transform.position += new Vector3(0, groundDistance, 0);
- }
- #endregion
- #region Private Functions
- private float CalculateGroundDistance()
- {
- // Calculating global scale.
- float radius = (Mathf.Max(transform.lossyScale.x, transform.lossyScale.z) * capsule.radius) + collisionBuffer;
- float height = capsule.height * transform.lossyScale.y;
- // Caluclating global position.
- Vector3 castPosition = transform.TransformPoint(capsule.center) + new Vector3(0, radius, 0);
- if (Physics.SphereCast(castPosition, radius, Vector3.down, out RaycastHit hit, height, groundLayer)) {
- hit.distance -= height / 2;
- }
- float angle = Vector3.Angle(hit.normal, Vector3.up);
- return angle > slopeAngle ? 0 : hit.distance;
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement