Unity Topdown 2D, how to make ball animation stop when its speed reaches zero?

Viewed 24

I have this topdown 2D game with a ball. I want it to roll around when touched by a player/collider, and then stop when speed of the ball reaches zero (and maybe slow the animation down before that too).

I've made the animation and implemented it through an Animator with an idle and a moving state. I also have 2D Circle Collider, 2D Rigidbody and all that. For now it works, but the problem is that it doesn't stop when its speed reaches zero. Is there a way to find its given speed in any moment of time, and then stop the animation once this number is less than 0.1 m/s?

Below is the script applied to the ball:

public class BallMove : MonoBehaviour
{  
   public Rigidbody2D rb;
   public Animator animator;

      void OnCollisionEnter2D(Collision2D other)
      { 
        if (other.gameObject.tag == "Player" || other.gameObject.tag == "Collider")
        { 
          animator.Play("Motion_Move");
        }
    }
}
1 Answers

I would change it so it reads the magnitude of the rigidbody's velocity, and determines animation speed by that. This way, when the velocity is 0, it will not play the animation anymore.

Something like

public class BallMove : MonoBehaviour
{
   public float animSpeed; 
   public Rigidbody2D rb;
   public Animator animator;

   void Start()
   {
      animator.Play();
   }
   void Update()
   {
      float vel = rb.velocity.magnitude;
      animator.speed = vel * animSpeed;
   }
}
Related