# Unity groundedness detection with collision normals

Feb 4th, 2023
1,135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. using System.Collections;
2. using System.Collections.Generic;
3. using UnityEngine;
4.
5. enum Groundedness {
6.     AIRBORNE,
7.     SLIPPING,
8.     GROUNDED
9. }
10. //because of how Enums work, these 3 states correspond to the numbers 0, 1, & 2 respectively
11. //so it's true that AIRBORNE < SLIPPING < GROUNDED
12. public class GroundedExample : MonoBehaviour
13. {
14.     Groundedness groundState = Groundedness.AIRBORNE;
15.     public float groundedThresholdAngle = 45; //maximum slope angle that's still considered grounded (in degrees)
16.     float groundedThresholdCosine; //cosine of above value
17.     public float slippingThresholdAngle = 80; //maximum slope angle that's not considered just a wall (in degrees)
18.     float slippingThresholdCosine; //cosine of above value
19.     Vector3 upwards = new Vector3(0,1,0); //this can be changed if wanted
20.
21.     void Start()
22.     {
23.         float groundedThresholdCosine = Mathf.Cos(groundedThresholdAngle * Mathf.Deg2Rad);
24.         float slippingThresholdCosine = Mathf.Cos(slippingThresholdAngle * Mathf.Deg2Rad);
25.     }
26.
27.     void FixedUpdate() {
28.         //FixedUpdate happens before the OnCollision functions
29.         //put this at the end of FixedUpdate
30.         //or, if you're manually calling Physics.Simulate, put this right before that
31.         groundState = Groundedness.AIRBORNE;
32.     }
33.
34.     void Update()
35.     {
36.         //Update happens after the OnCollision functions
37.     }
38.     void OnCollisionStay(Collision collisionInfo) {
39.         foreach (ContactPoint contact in collisionInfo.contacts) {
40.             float slopeCosine = Vector3.Dot(contact.normal, upwards);
41.             //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
42.             if (slopeCosine >= groundedThresholdCosine) {
43.                 if (groundState < Groundedness.GROUNDED) {
44.                     groundState = Groundedness.GROUNDED;
45.                 }
46.             }
47.             else if (slopeCosine >= slippingThresholdCosine) {
48.                 if (groundState < Groundedness.SLIPPING) {
49.                     groundState = Groundedness.SLIPPING;
50.                 }
51.             }
52.         }
53.     }
54. }
55.
Tags: