简体   繁体   English

如何理解玩家是否在统一移动

[英]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.我制作了一个导航网格 controller,我的玩家移动到触摸或点击的地方,但我希望玩家在移动时播放行走动画,但当它到达目的地而不移动时,播放空闲 animation。

Please explain in C#.请在 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);
            }
        }
    }
}

You can use the "NavMeshAgent.remainingDistance" property to check if it is within a small range.您可以使用“NavMeshAgent.remainingDistance”属性来检查它是否在一个小范围内。 Here is the doc on navmeshagent for more 这是关于 navmeshagent 的文档以获取更多信息

(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.我建议不要对小于值进行硬编码,因为在检查器中调整它会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM