I’m having trouble understanding this behavior. Here is a simplified version of my code:
//Decelerating
void FixedUpdate() {
float dashDecel = Mathf.MoveTowards(rb.velocity.x, 0, 125 * Time.deltaTime);
rb.velocity = new Vector3(dashDecel, rb.velocity.y, 0);
}
//Printing the velocity then exiting state when velocity is below 10f.
void Update() {
case Dash:
print(Mathf.Abs(rb.velocity.x));
if (Mathf.Abs(rb.velocity.x) < 10f) ExitState();
break;
}
When I dash in the right direction (this is a 2d platformer) the dash state consistently exits when the velocity reads 7.50. When I dash in the left direction, it exits at 10.00. I’m not understanding why the state exits at 10 when i’m testing for under 10. Is this just inconsistency when comparing a float, like every time I dash left the velocity is actually 9.99999 and 10.00001 when I dash right?
Well that is a bit difficult to tell like this. It would be interesting to see how you set the speed value for your dash. In general i’d say it is indeed an issue of floating imprecisions but it is absolutely clear why those values:
Assume at the start of your dash you will set the speed to 15.
Now each frame we substract exactly 2.5 from this as Time.deltaTime in FixedUpdate is always 0.02f.
So given float imprecision is really the issue here and the negative version checks the value against 9.999999 while the positive version ends up at 10 then it is solved.
So unless this is really important or something i’d suggest that you just change your check to be
if(abs(....) < 10.5)
and you are good to go.
Did you try printing the velocity with all decimals?
Other then that it might be interesting to compare the binary representation of the original value with the one returned from Math.Abs().