CharacterController.velocity not working properly?

if (playerHead.transform.localRotation.x >= 0.59f) {
    character.transform.Rotate(new Vector3(turnSpeed * Time.deltaTime, 0, 0));
} else if (playerHead.transform.localRotation.x <= -0.59f) {
    character.transform.Rotate(new Vector3(- turnSpeed * Time.deltaTime, 0, 0));
}

This is my script (I know it’s not perfect, but it works ok for now), that rotates the body when the head is at a specific angle (so that my head doesn’t spin 360 degrees while my body is staying still). And here is my code snippet which plays the animations:

if (characterController.velocity == Vector3.zero)
{
    animator.Play("idle");
    return;
}
if (characterController.velocity.z < 0)
{
    animator.Play("walkBack");
    return;
}
if (isRunning)
{
    animator.Play("run");
    return;
}
if (!isRunning)
{
    animator.Play("walk");
    return;
}

What is happening, is that if I move towards negative Z, then the characterController.velocity.z < 0 thinks I am moving backwards. How can I fix that? Thank you!

I’m pretty sure CharacterController.velocity is in world space units, not local space. Try using Transform.InverseTransformDirection to convert it to local space units before checking that it is less than 0.

I tried what you said like this:

if (transform.InverseTransformDirection(characterController.velocity).z < 0)

And it didn’t work, the same thing keeps happening.

Add debugging for transform.InverseTransformDirection(characterController.velocity).z to see exactly what value it is getting.

When moving positive z, it’s aprox. 1.4. When moving negative z, -1.4.