RigidBody.IsSleeping delay

im using a script to control when my characters walking animation is on or off. when the character is standing still its obviously off, when its moving its on. i use this code

if (GetComponent<Rigidbody2D>().IsAwake())
        {
            Walk.SetBool("WalkStop", false);
            Walk.SetBool("WalkStart", true);

        }

        if (GetComponent<Rigidbody2D>().IsSleeping())
        {
            Walk.SetBool("WalkStop", true);
            Walk.SetBool("WalkStart", false);

        }

everything is fine with the first part but when it gets to stoping the animation it has about a one second delay. when the player stops pressing the Movment keys the player comes to a halt but it does have a delay to make it smoother. but this is interfering with the issleeping code. i think the issleeping is only true if its at a 100% stop. how to i test if my character is near enough to a standstill to turn off the animation?

Rigidbody sleeping is an optimization of the physics engine, not a reliable way to tell if a rigidbody is moving or not. As you could tell, when a rigidbody falls asleep is not clearly defined and might also change when Unity updates PhysX.

Instead, check if velocity magnitude of the irgidbody is below a certain value. The velocity is updated every fixed update and will immediately fall when the rigidbody comes to a halt.

2 Likes
private Vector2 vel;
void Start(){

} 
void Update()
    {
  
Debug.Log(vel);

 if (vel.magnitude < .5f)
        {
            Walk.SetBool("WalkStop", true);
            Walk.SetBool("WalkStart", false);

        }
}

this is what i have so far but the vel always returns a value of 0 what am i doing wrong

1 Like

Uhm, “vel” is just a member variable of your class. Unless you do something to that variable of course it will has it’s default value of (0,0,0) which has a magnitude of 0. Since you use 2d physics you just want to grab the velocity of the Rigidbody2D component

Rigidbody2D rb;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    bool isMoving = rb.velocity.sqrMagnitude > 0.25f;
    Walk.SetBool("WalkStop", !isMoving);
    Walk.SetBool("WalkStart", isMoving);
}
3 Likes

ooooooohhhhhh thank you