- Home /
How to check if an object is upside-down?
I am making a racing game, and I need to be able to check if a player or AI car is flipped upside down. I have tried using the vehicle's X and Z euler angles to check, but it is not working very well because the values jump due to the obvious problem of gimbal lock. Does anyone know of a way to check using Quaternions?
Answer by NoseKills · Jul 09, 2015 at 09:09 PM
Something like
if (Vector3.Dot(transform.up, Vector3.down) > 0)
// car's up-vector has a down facing component
The dot product is greater than 0 if the car's roof is pointing even slightly downward and it equals 1 when the cars up-vector points to the same direction as Vector3.down (totally upside down). It's also a very fast calculation.
You could find a value between 0 and 1 that works well for you
Thanks, works without any of the weird effects of my method!
Yeah, but how can one check also if the car is sideways (rotated around Z +-90°; Door touches ground)?
If we base that on the usage of dot product, it can be deter$$anonymous$$ed rather inexpensively by using a pair of them:
// C#
if($$anonymous$$athf.Abs(Vector3.Dot(transform.up, Vector3.down)) < 0.125f)
{
// Car is primarily neither up nor down, within 1/8 of a 90 degree rotation
// Therefore, check whether it's on either side. Otherwise, it's on front/back
if($$anonymous$$athf.Abs(Vector3.Dot(transform.right, Vector3.down)) > 0.825f)
{
// Car is within 1/8 of a 90 degree rotation of either side
}
}
Because the dot product of two normalized vectors will also have a length of 1, a generalized angle can be calculated from the result.
Using absolute value, I'm taking an either-or, so I'm looking for a value in which the top/bottom is nearly parallel to the ground.
If so, then I deter$$anonymous$$e whether either side is nearly perpendicular to the ground. If so, the car is lying (basically) on its side.
Your answer
Follow this Question
Related Questions
inertiaTensor stopping automatic rotation 1 Answer
transform.Translate moving while upside down? 1 Answer
Find GameObject Position(x,z) and rotation(y) 1 Answer
Random Turning? 1 Answer
transform position y changes when character rotates 0 Answers