RigidBody2D y velocity is greater than Epsilon
I know there are plenty questions like this when people compare float on exactly match. Here my code:
void Update()
{
Move(_moveKeyInput);
}
private void Move(float data)
{
var rigidbody2DVelocity = _rigidbody2D.velocity;
print(rigidbody2DVelocity + "; " + (Mathf.Approximately(rigidbody2DVelocity.y, 0f)));
_rigidbody2D.velocity = new Vector2(data * velocity, rigidbody2DVelocity.y);
var hasHorizontalSpeed = Mathf.Abs(rigidbody2DVelocity.x) > Mathf.Epsilon;
}
public void OnMove(InputAction.CallbackContext context)
{
_moveKeyInput = context.ReadValue<float>();
}
Somehow if _moveKeyInput is not zero (key is pressed) then Mathf.Approximately(rigidbody2DVelocity.y, 0f) is false, rigidbody2DVelocity.y, > Mathf.Epsilon is true.
I'm using Unity 2020.1.04b
Answer by streeetwalker · Apr 05, 2020 at 07:48 AM
Hi @Robert-Paulson, because you're dealing with the physics engine, do you own checks and don't rely on epsilon or approximately - it's a black box and it's difficult to predict where and when forces not under your direct control affect an object.
First, decide on a minimum velocity threshold. Set your velocities to zero at the start of your game, and in your animation loops if they are below that, Use the same threshold if you need to test to do something based on a condition.
// is velocity less than 100 micrometers?
if( _rigidbody2D.velocity.magnitude < 0.001f ) _rigidbody2D.velocity = Vector3.zero;