- Home /
How to calculate the speed at which a rigidbody2d is actually moving ?
I am trying to figure out the speed of a rigidbody2D (it's velocity) (It's movement speed) so that I can animate a character. I need the character to stop the walking animation when it hits a wall (stops moving) The problem is that when my character walks into a wall, if the key is still held, I am still adding to the velocity. Therefore my code still thinks that it should try to play the walking animation.
Is there any code to determine the actual speed at which a rigid body is moving and not just being set to? Is there any better way of telling the animator to stop the animation when the player isn't moving?
I need a quickly updating solution. I have tried:
if (GetComponent<Rigidbody2D>().isSleeping())
and
if (gameObject.isStatic)
but they either don't work or are too slow at recognising that the player has stopped. Please help me solve this problem.
My current solution is:
if (rb.velocity == 0) {
anim.SetFloat ("Speed", 1);
} else {
anim.SetFloat ("Speed", 0);
}
Answer by Tomer-Barkan · Sep 28, 2015 at 04:28 PM
I would keep a parameter "last position", and every frame calculate the change in position from the previous frame. This will give you the actual speed in the last frame. All your calculations will be off by one frame, but that shouldn't be noticeable.
Your answer
Follow this Question
Related Questions
Comparing rigidbody speeds 1 Answer
Velocity powered rigidbody on a moving platform without parenting. 3 Answers
Mecanim Inherit Velocity of previous animation? 0 Answers
How do I raise the speed of the pinball without raising flipper speed to insane levels? 3 Answers
Calculating speed of rigidbody? 1 Answer