Unity does not return negative angles

In Unity 5.3, I do not get negative values.
Therefore I check the angle value, and if it is 180 degrees or greater, I subtract it from 360.

public bool IsStanding()
{
    float tiltX = (transform.eulerAngles.x < 180f) ? transform.eulerAngles.x : 360 - transform.eulerAngles.x;
    float tiltZ = (transform.eulerAngles.z < 180f) ? transform.eulerAngles.z : 360 - transform.eulerAngles.z;

    if (tiltX > standingThreshold || tiltZ > standingThreshold)
    {
        return false;
    }
         
    return true;
}
4 Likes

Good solution

I had this issue as well in 5.4. No clue why this occured from 5.3 on.

Took me a bit to figure out the code above. A bit of an obfuscatory way to write if statements, but I like the conciseness of it. Thanks for the help, TorrqTB.

I’m a bit bullheaded when it comes to coding solutions and sometimes just stare at code and will it to work because it “should work”. :slight_smile:

1 Like

Yes I know I am necroing the thread, but I had several questions about the code above because I am not yet used to coding shorthand. The code fix work brilliantly… but I wanna know HOW it worked if someone does not mind explaining. So… to my questions:

What exactly is ? and : shorthand for in the 2 float lines?

and (even though I think I figured out this last one)

Within the if statement, is || the same as &&?

Thanks in advanced for any answers. I like the shorthand, but I do not want to use code that I have no idea how to reproduce because I don’t get the reference. :slight_smile:

Hey Eric, the ? and : symbols are part of the ternary operator for a conditional expression. Essentially it’s a short hand way of writing an if / else statement.

Take the first tiltX float as an example:

float tiltX = (transform.eulerAngles.x < 180f) ? transform.eulerAngles.x : 360 - transform.eulerAngles.x;

The part before the ‘?’ ( (transform.eulerAngles.x < 180f) ) is the condition, to the left of the ‘:’ is the True expression, and to the right is the false expression.

//condition ? true_expression : false_expression;

Depending on the result of the condition, in this case the transform.eulerAngles.x being less then 180, tiltX is assigned either the transform.eulerAngle.x, or 360 minus the transform.eulerAngle.x.

For comparison, an alternate way of writing it as an if / else statement could look like this:

float tiltX = 0.0f;

if (transform.eulerAngles.x < 180f) 
{
    tiltX = transform.eulerAngles.x;
}
else 
{
    tiltX = 360 - transform.eulerAngles.x;
}

And the ‘||’, is the conditional-OR operator. Simply meaning if the left OR right expressions return true, the code inside the curly braces runs.

Hopefully this helps!

4 Likes

@Lemniscate thank you! That explains it exactly :slight_smile: Its nice to know the operators for shorthand, but I have a bit of OCD. If most of my code runs one way… all of it needs to run that way for consistency.

Privacy & Terms