Need help changing animations from script!

So I am working on a game, and trying to make a nice fpscontroller with some working animations.

Everything has been working fine until I wanted to add a CrouchIdle animation. I hade a CrouchWalk animation, but it looks kinda scuffed if you stop move and the characters legs keeps on walking. I have tried a lot of different fixes, but nothing seems to work. I have a param in Animator called "crouch", meant to be on the idle one. I have another call "CrouchWalkForward". All other animations works perfect, but I need this to work with wether I’m moving or idling.

This is what I got:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Diagnostics;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movement")]
    private float moveSpeed;
    public float walkSpeed;
    public float sprintSpeed;
    public float sneakSpeed;

    public float groundDrag;

    [Header("Jumping")]
    public float jumpForce;
    public float jumpCooldown;
    public float airMultiplier;
    bool readyToJump;

    [Header("Crouching")]
    public float crouchSpeed;
    public float crouchYScale;
    private float startYScale;

    [Header("Keybinds")]
    public KeyCode jumpKey = KeyCode.Space;
    public KeyCode sprintKey = KeyCode.LeftShift;
    public KeyCode crouchKey = KeyCode.LeftControl;
    public KeyCode sneakKey = KeyCode.LeftAlt;

    [Header("Ground Check")]
    public float playerHeight;
    public LayerMask whatIsGround;
    bool grounded;

    [Header("Slope Handling")]
    public float maxSlopeAngle;
    private RaycastHit slopeHit;
    private bool exitingSlope;

    public Transform orientation;

    float horizontalInput;
    float verticalInput;

    public Animator animator;

    Vector3 moveDirection;

    Rigidbody rb;

    public MovementState state;
    public enum MovementState
    {
        walking,
        sprinting,
        crouching,
        sneaking,
        air
    }

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
        animator = GetComponentInChildren<Animator>();

        readyToJump = true;

        startYScale = transform.localScale.y;
    }

    private void Update()
    {
        // ground check
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);

        MyInput();
        SpeedControl();
        StateHandler();

        // handle drag
        if (grounded)
            rb.drag = groundDrag;
        else
            rb.drag = 0;
    }

    private void FixedUpdate()
    {
        MovePlayer();
        RotatePlayer();
    }

    private void MyInput()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");

        // when to jump
        if (Input.GetKey(jumpKey) && readyToJump && grounded)
        {
            readyToJump = false;

            Jump();

            Invoke(nameof(ResetJump), jumpCooldown);
        }

        // start crouch
        if (Input.GetKeyDown(crouchKey))
        {
            transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
            rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
        }

        // stop crouch
        if (Input.GetKeyUp(crouchKey))
        {
            transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
        }
    }

    private void StateHandler()
    {
        bool isActuallyMoving = rb.velocity.magnitude > 0.5f;

        // Mode - Crouching
        if (Input.GetKey(crouchKey))
        {
            state = MovementState.crouching;
            moveSpeed = crouchSpeed;
            if(isActuallyMoving)
            {
                animator.SetBool("CrouchWalkForward", true);
            }
            else if (!isActuallyMoving) 
            {
                animator.SetBool("Crouch", true);
            }
        }

        // Mode - Sprinting
        else if (grounded && Input.GetKey(sprintKey))
        {
            state = MovementState.sprinting;
            moveSpeed = sprintSpeed;
        }

        // Mode - Sneaking
        else if (grounded && Input.GetKey(sneakKey))
        {
            state = MovementState.sneaking;
            moveSpeed = sneakSpeed;
        }

        // Mode - Walking
        else if (grounded)
        {
            state = MovementState.walking;
            moveSpeed = walkSpeed;
        }

        // Mode - Air
        else
        {
            state = MovementState.air;
        }

        // Reset all parameters to ensure no conflicts
        animator.SetBool("Walk", false);
        animator.SetBool("Sprint", false);
        animator.SetBool("Sneak", false);
        animator.SetBool("IsInAir", !grounded);

        // Update animator based on the state
        switch (state)
        {
            case MovementState.walking:
                animator.SetBool("Walk", isActuallyMoving);
                break;
            case MovementState.sprinting:
                animator.SetBool("Sprint", isActuallyMoving);
                break;
            case MovementState.sneaking:
                animator.SetBool("Sneak", isActuallyMoving);
                break;
        }
    }

    private void MovePlayer()
    {
        // calculate movement direction
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

        // on slope
        if (OnSlope() && !exitingSlope)
        {
            rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 20f, ForceMode.Force);

            if (rb.velocity.y > 0)
                rb.AddForce(Vector3.down * 80f, ForceMode.Force);
        }

        // on ground
        else if (grounded)
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);

        // in air
        else if (!grounded)
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);

        // turn gravity off while on slope
        rb.useGravity = !OnSlope();
    }

    private void SpeedControl()
    {
        // limiting speed on slope
        if (OnSlope() && !exitingSlope)
        {
            if (rb.velocity.magnitude > moveSpeed)
                rb.velocity = rb.velocity.normalized * moveSpeed;
        }

        // limiting speed on ground or in air
        else
        {
            Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

            // limit velocity if needed
            if (flatVel.magnitude > moveSpeed)
            {
                Vector3 limitedVel = flatVel.normalized * moveSpeed;
                rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
            }
        }
    }

    private void Jump()
    {
        exitingSlope = true;

        // reset y velocity
        rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    }
    private void ResetJump()
    {
        readyToJump = true;

        exitingSlope = false;
    }

    private bool OnSlope()
    {
        if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
        {
            float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
            return angle < maxSlopeAngle && angle != 0;
        }

        return false;
    }

    private Vector3 GetSlopeMoveDirection()
    {
        return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
    }

    private void RotatePlayer()
    {
        // Align player's Y-axis rotation with the orientation transform
        Vector3 orientationDirection = orientation.eulerAngles;
        orientationDirection.x = 0; // Keep player's original X-axis rotation
        orientationDirection.z = 0; // Keep player's original Z-axis rotation
        Quaternion newRotation = Quaternion.Euler(orientationDirection);
        rb.MoveRotation(newRotation);
    }
}

What about just setting a speed float parameter in the animator? If the player is crouched not moving, the animator state speed might just be 0, then the legs wouldn't move.

–

2 Answers

2

The behavior depends on how your state transition conditions are set up in the Animator. But I expect the problem is that you never set CrouchWalkForward to false. You should probably set this bool to false when you are not crouch walking.

  if(isActuallyMoving)
  {
      animator.SetBool("CrouchWalkForward", true);
  }
  else
  {
      animator.SetBool("CrouchWalkForward", false);
      animator.SetBool("Crouch", true);
  }

Animator Controller also has something called “Layers”. You can use it for animations that should run at the same time another animation is running.

Add a new layer and set up the crouch transition there. Don’t forget to change the “weight” of the layer

Here’s a link to unity manual on animation layers

Animation Layers Unity Docs