控制人物和动画走动

控制人物和动画走动

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<Animator>();
        mRigidbody = GetComponent<Rigidbody>();
    }
    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>();
        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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值