basically I have a character that needs to change from idle to walk position when it’s moving. I’ve placed it inside an empty object (Character Parent) that I’m moving in the Z axis using animation (so it should have a Z velocity) and have defined the character parent as a rigidbody. Yet Z velocity using Debug.log(rb.velocity.z) shows up as 0. Here is my script, I’ve tried enabling “Animate Physics” but that didn’t work. New to unity so I’m sure this is a simple fix
public class IdleToWalk : MonoBehaviour
{
public Animator animate;
public bool isWalking;
void Start()
{
animate = this.gameObject.GetComponent<Animator>();
}
void Update()
{
Rigidbody rb = GetComponentInParent<Rigidbody>();
if (rb.velocity.z == 0) animate.SetBool("isWalking", false);
else animate.SetBool("isWalking", true);
}
}
@gitlinjoss I assume your animation moves the character instead of adding a velocity to its rigidbody. So only transform.position.z changes and not rigidbody.velocity.z
Few problems here!
First, you shouldn’t move a rigidbody using its transform. Because you are doing that, the rigidbody doesn’t realize it is moving, and therefore velocity is always 0.
Your other problem is that your animation speed might not match your actual speed. You could use SetFloat to send the z velocity to your animator, so that you can accelerate the animation when needed.
To move a rigidbody, there’s a few different tools:
If it is not kinematic, use rigidbody.velocity or rigidbody.AddForce. For example
rigidbody.velocity = Vector3.forward * Input.GetAxis("Vertical") * playerSpeed;
If it is kinematic, use MovePosition:
rigidbody.MovePosition(rigidbody.position + Vector3.forward * (Input.GetAxis("Vertical") * playerSpeed * Time.fixedDeltaTime));
If you use a CharacterController, use 1 or SimpleMove.
Only use transform.position if you don’t have a rigidbody or CharacterController.
Only use rigidbody.position if you want to teleport your rigidbody instead of moving it continuously.