Run to Idle Animation not working.

The character does not transition back to idle from run animation. (I am not a native speaker of English sorry.)There is no problem when Idle to Run animation on character, But when running to idle, the character still running instead of idle. It’s an isometric camera view 3D unity project. I am new so need help here is the code: (In my opinion, the problem is about the if statement but I don’t know how to check the character is moving parameter.)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class CharController : MonoBehaviour
{
    [SerializeField]
    float moveSpeed = 4f;

    Vector3 forward, right;

    private Animator animator;
    


    
 

    void Start()
    {
        animator = GetComponent<Animator>();
        forward = Camera.main.transform.forward;
        forward.y = 0;
        forward = Vector3.Normalize(forward);
        right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
    }

    
    void Update()
    {

        if (Input.anyKey)

        { 
            Move(); 
        
        }

        

    }
    void Move()
    {
        Vector3 direction = new Vector3(Input.GetAxis("HorizontalKey"), 0, Input.GetAxis("VerticalKey"));
        Vector3 rightMovement = right * moveSpeed * Time.deltaTime * Input.GetAxis("HorizontalKey");
        Vector3 upMovement = forward * moveSpeed * Time.deltaTime * Input.GetAxis("VerticalKey");

        Vector3 heading = Vector3.Normalize(rightMovement + upMovement);

        transform.forward = heading;
        transform.position += rightMovement;
        transform.position += upMovement;




        if (direction.magnitude > 0.001f)
        {
            animator.SetBool("IsMoving", true);
        }

        else
        {
            animator.SetBool("IsMoving", false);

        }
        

    }
}

You could try to write something like

    bool isMoving = ( Input.GetButton( "Horizontal" ) || Input.GetButton( "Vertical" ));  //Determine if the player is pressing a move-key
    
if( animator.GetBool( "IsMoving" ) != isMoving ) {
animator.SetBool( "IsMoving", isMoving );
}

Just another approach to your code, if it doesn’t work you could take a look at the move->idle transition in your Animator Controller and make sure that the condition for entering the transition is that “IsMoving” is set to false. ( ie. idle-to-move has IsMoving set to true, while move-to-idle has the opposite )