控制人物和动画走动

控制人物和动画走动

public class PlayerMovement : MonoBehaviour
{
    //定义人物旋转速度
    public float mTurnSpeed = 20f;
    public Animator mAnimator;
    public Rigidbody mRigidbody;
    Vector3 mMovement; //移动矢量
    Quaternion mRotation = Quaternion.identity; //旋转角度
    // Start is called before the first frame update
    void Start()
    {
        mAnimator = GetComponent();
        mRigidbody = GetComponent();
    }
    private void FixedUpdate()
    {
        //获取水平竖直是否有键值输入
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        //设置任务移动方向
        mMovement.Set(horizontal, 0f, vertical);
        mMovement.Normalize();

        //定义游戏人物移动Bool值
        bool hasHorizontalInput = !Mathf.Approximately(horizontal, 0f);
        bool hasVerticalInput = !Mathf.Approximately(vertical, 0f);
        bool isWalking = hasHorizontalInput || hasVerticalInput;
        mAnimator.SetBool("IsWalking", isWalking);

        //旋转过渡
        Vector3 desirForward = Vector3.RotateTowards(transform.forward,mMovement,mTurnSpeed * Time.deltaTime ,0f);
        mRotation = Quaternion.LookRotation(desirForward);
    }
    //Animator 执行时调用
    //游戏人物旋转和移动,旋转过渡通过三元数转四元数方式获取人物当前应有角度
    private void OnAnimatorMove()
    {
        mRigidbody.MovePosition(mRigidbody.position + mMovement * mAnimator.deltaPosition.magnitude);
        mRigidbody.MoveRotation(mRotation);
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

设置怪物自动走动,多个目标点往返走动

public class WayPointPatrol : MonoBehaviour
{
    private NavMeshAgent navMeshAgent;
    public Transform[] waypoints;

    //当前巡逻的目标点
    int m_CrrentPointIndex;
    // Start is called before the first frame update
    void Start()
    {
        navMeshAgent = GetComponent();
        navMeshAgent.SetDestination(waypoints[0].position); //先从起点到达第一个巡逻点
    }

    // Update is called once per frame
    void Update()
    {
        //到达目标点,前往下一个目标点    “<=”  划重点
        if (navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
        { 
            m_CrrentPointIndex = (m_CrrentPointIndex + 1)%waypoints.Length;   //可以让目标在路径点上来回往返走动
            navMeshAgent.SetDestination(waypoints[m_CrrentPointIndex].position);
        }
    }
}

你可能感兴趣的:(动画)