sarrenta
sarrenta

Reputation: 23

How to understand if player is moving or not in unity

I make a navmesh controller and my player move to the touched or clicked place but I want the player to play a walking anime when is moving but when it reaches the destination and not moving play idle animation.

Please explain in C#.

I made script it play walking but it doesn't play idle when player reaches its destination

public class navmesh : MonoBehaviour
{
    UnityEngine.AI.NavMeshAgent agent;
    public Animator anim;
    public Transform player;
    public GameObject obj;

    void Start()
    {
        agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mouse = Input.mousePosition;
            Ray castPoint = Camera.main.ScreenPointToRay(mouse);
            RaycastHit hit;

            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
            {
                agent.destination = hit.point;

                anim.SetBool("walk", true);

                obj.transform.position = hit.point;
            }
            else
            {
                anim.SetBool("walk", false);
            }
        }
    }
}

Upvotes: 2

Views: 1863

Answers (1)

CodingGuy
CodingGuy

Reputation: 81

You can use the "NavMeshAgent.remainingDistance" property to check if it is within a small range. Here is the doc on navmeshagent for more

(example)

if(agent.remainingDistance > 0.1f) {
  // Play anims
  
}

I would recommend not hard-coding that less-than value as it can be nicer to adjust it in the inspector.

Upvotes: 2

Related Questions