How to detect if an object is upright?

How to detect if an object is upright?

I have a cartoon car and it has a skid sound with the car skids. But when the car flips over the skid sound plays endlessly and its really annoying. I have a basic script that is meant to detect when the car is upright and only play the skid sound with the car is upright. Here is the code:
This script is on the car itself:
public bool IsUpright () {
        Vector3 rotationInEuler = transform.rotation.eulerAngles;

        float tiltX = Mathf.Abs(rotationInEuler.x);
        float tiltZ = Mathf.Abs(rotationInEuler.z);

        if(tiltX < uprightThreshold && tiltZ < uprightThreshold){
            return true;
            return false;

This script is on a skid sound prefab:
void Update () {
                transform.GetComponent().GetGroundHit(out tireHit);
                currentFrictionValue = Mathf.Abs(tireHit.sidewaysSlip);

                if(skidAt <= currentFrictionValue && skidWait <= 0){
                    Instantiate(skidSound, tireHit.point, Quaternion.identity);
                    skidWait = 1;
                skidWait -= Time.deltaTime * skidEmission;

When the IsUpright bool (first script) is printed to the console it keeps flickering between true and false and it isn't detecting when the car is upright. By the way the uprightThreshold from the first script has a value of 40. I have also check in the inspector and the rotation of the car on both the x and z axis are not constant at 0, it is flickering up and down between about 1 and -1, but unfortunately unity doesn't support having negative rotation values, so rather it goes to 359, which is mucking up the system. Could someone show me how to fix this? Thanks in advance.


Answer 1:

I would not complicate things much:

public bool IsUpright () {
        return transform.up.y > threshold;/*say 0.6 ?*/

because the up vector is normalized and, naturally, points upwards you just need to check its length in Y axis(or the "up" axis if you use different one). It will be 1.0 when perfectly up and -1.0 if perfectly upside down. This simple code will suffice - if you don't require exact angle, of-course(you can still compute the equivalent Y threshold value of angle should you require it).