# 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;
}else{
return false;
}
}


This script is on a skid sound prefab:

void Update () {
if(motor.IsUpright()){
if(motor.IsMoving()){
transform.GetComponent<WheelCollider>().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.

public bool IsUpright () {

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).
• Thank you for this! I have an error however, "Assets/Scripts/Motor.cs(247,43): error CS1061: Type UnityEngine.Quaternion' does not contain a definition for up' and no extension method up' of type UnityEngine.Quaternion' could be found (are you missing a using directive or an assembly reference?)" Nov 10, 2015 at 19:11
• @Matthew Inglis, it sounds as though you've tried to use transform.rotation.up which doesn't exist, instead of transform.up — maybe a typo when converting from your old code? Nov 10, 2015 at 21:43