Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- enum Groundedness {
- AIRBORNE,
- SLIPPING,
- GROUNDED
- }
- //because of how Enums work, these 3 states correspond to the numbers 0, 1, & 2 respectively
- //so it's true that AIRBORNE < SLIPPING < GROUNDED
- public class GroundedExample : MonoBehaviour
- {
- Groundedness groundState = Groundedness.AIRBORNE;
- public float groundedThresholdAngle = 45; //maximum slope angle that's still considered grounded (in degrees)
- float groundedThresholdCosine; //cosine of above value
- public float slippingThresholdAngle = 80; //maximum slope angle that's not considered just a wall (in degrees)
- float slippingThresholdCosine; //cosine of above value
- Vector3 upwards = new Vector3(0,1,0); //this can be changed if wanted
- void Start()
- {
- float groundedThresholdCosine = Mathf.Cos(groundedThresholdAngle * Mathf.Deg2Rad);
- float slippingThresholdCosine = Mathf.Cos(slippingThresholdAngle * Mathf.Deg2Rad);
- }
- void FixedUpdate() {
- //FixedUpdate happens before the OnCollision functions
- //put this at the end of FixedUpdate
- //or, if you're manually calling Physics.Simulate, put this right before that
- groundState = Groundedness.AIRBORNE;
- }
- void Update()
- {
- //Update happens after the OnCollision functions
- }
- void OnCollisionStay(Collision collisionInfo) {
- foreach (ContactPoint contact in collisionInfo.contacts) {
- float slopeCosine = Vector3.Dot(contact.normal, upwards);
- //this value is 1 if this collision is with flat ground, 0 if it's with a wall, and -1 if it's with a ceiling
- if (slopeCosine >= groundedThresholdCosine) {
- if (groundState < Groundedness.GROUNDED) {
- groundState = Groundedness.GROUNDED;
- }
- }
- else if (slopeCosine >= slippingThresholdCosine) {
- if (groundState < Groundedness.SLIPPING) {
- groundState = Groundedness.SLIPPING;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement