- Home /
.normalized sometimes returns 0 values, in a condition that only functions if value is not 0...
I'm having a bit of an issue with this very simple bit of code. I'll show it first:
if(rigidbody2D.velocity.x != 0)
{
Debug.Log ("Velocity Direction: " + new Vector2(rigidbody2D.velocity.x,0).normalized.x);
}
As you can see, if my X velocity is higher/lower than 0, then we log the normalized direction of that velocity. Yet when I'm turning back and forth, resulting in a very slow X velocity, or turning on a slope, it will result in some 0 values, despite it only triggering if my .X velocity is not 0... (and this isn't an issue with the if statement I don't think, as it doesn't log anything if I stand still)
Does .normalized just round down the value if it's super close to 0? And if so, what do you think I could use instead to get around this issue?
I'm guessing it is the Debug.Log() that is rounding or truncating the value. $$anonymous$$aybe you want to use a threshold:
if ($$anonymous$$athf.Abs(rigidbody2D.velocity.x) > someValue) {
Unfortunately that doesn't solve the problem, it would seem it's an issue with the .normalized and not the condition. =/
Answer by DajBuzi · Feb 11, 2014 at 08:47 AM
Your Vector is toomsmall to be normalized. As it's stated in documentation:
"If the vector is too small to be normalized a zero vector will be returned."
Dang =/ Guess I'll just have to do a workaround by adding an condition in my code to only update the float if the normalized value is also not 0. Unless there's another operation that I could use which would work similar to normalized... Thanks.
If you want to just set this value between 0.0 and 1.0 then Robertbu gaved you solution, but if you want set ot from -1.0 to 1.0 then... i'm guessing that you should use $$anonymous$$athf.Clamp <- it's only a guess :p
Nah, I need it to either be -1 if it's below 0, or 1 if above 0. Robert's solution would still allow for that, as it's only changing the condition, not the result. The issue, as you mentioned, arises from Normalized not handling that low of values.
Clamp would also only handle one direction. I think I'll just resort to using an if/else ins$$anonymous$$d, I don't need such micro-optimization anyway. So if the value is below, I'll just feed a -1 to the variable, and vice versa.
if(rigidbody2D.velocity.x > 0)
{
moveDir = 1;
}
else if(rigidbody2D.velocity.x < 0)
{
moveDir = -1;
}
After thinking on it a bit, I thought of a solution for the normalize value issue. I use the normalized value in my IF condition as well.
if(new Vector2(rigidbody2D.velocity.x,0).normalized.x != 0)
{
Debug.Log ("Velocity Direction: " + new Vector2(rigidbody2D.velocity.x,0).normalized.x);
}
And we're good to go. That way it knows if I'm going to be fed a 0 value by normalized and thus won't execute. Though I'll probably stick with the if/elseif, as it's likely more efficient than calculating the normalized value haha.