Why is this loop infinite?

I was using this loop to accelerate the rigidbody to a certain “maxSpeed”, but for some reason it was running infinitely.

while ( (rigidbody.velocity.sqrMagnitude) < (maxSpeed*maxSpeed)) {
			rigidbody.velocity += (moveDir.normalized * 0.5 );
			rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity,maxSpeed);
			yield WaitForFixedUpdate();

All the print statements print the same thing when the velocity reaches maxSpeed, which is 4||4.

After spending an hour trying to figure out what was wrong, I it changed from “sqrMagnitude” to “magnitude” and “maxSpeed*maxSpeed” to “maxSpeed” it worked fine.

Then later on I started using this if statement in another part of the code:

`print(rigidbody.velocity.magnitude +“||||”+ maxSpeed);


if ( rigidbody.velocity.magnitude == maxSpeed ) {
	state = "walk";
	newState = 1;

Again the print statement is printing the same number for magnitude and maxSpeed, but it’s not working. “sqrMagnitude” isn’t working either. Also, this code segment problem isn’t happening all the time. It depends on how fast the rigidbody accelerated to “maxSpeed”. Can someone explain to me how it can print the same number for “maxSpeed” and “rigidbody.velocity.magnitude” and not work. Also, explain to me why “sqrMagnitude” didn’t work for the first problem, and then “magnitude” worked.

Try using ‘Mathf.Approximately’ instead of the ‘==’ operator. It takes small floating point values into account, and so will give you a more accurate result.