I would like to ask if there's a built-in C# statement that would allow me to write the following with less lines of code:
float fH = Input.GetAxis("Horizontal"); //doesn't really matter where this comes from, but in this case, it's the user's input on a joystick
if (fH < 0)
{
fH = -1;
}
else if (fH > 0)
{
fH = 1;
}
else
{
//don't change anything
}
As far as I know, I can't use
fH = if(...)
because this would only allow for 2 cases while I need 3 cases (smaller than 0, bigger than 0 or 0).
Math.Sign will return whether the input is positive, negative, or 0 with only a single statement (no real need for the if at all).
Math.Sign(-2)
-1
Math.Sign(-3.3)
-1
Math.Sign(3)
1
Math.Sign(0)
0
It returns an int32, which you can reassign back to your float as you were doing.
fH = Math.Sign(fH);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With