首页 > 代码库 > Demo_玩家移动(主要注意动画的设置)

Demo_玩家移动(主要注意动画的设置)

技术分享技术分享

using UnityEngine;
using System.Collections;

public class NewPlayerMove : MonoBehaviour {

    private float hor,ver;
    private Animator ani;
    //转身速度
    public float turnSpeed = 10;

    void Awake()
    {
        ani = GetComponent<Animator> ();
    }

    void Update()
    {
        hor = Input.GetAxis ("Horizontal");
        ver = Input.GetAxis ("Vertical");
        //移动
        Move (ver);
        //转身
        Turn (hor, ver);
    }

    void Move(float ver)
    {
        if (ver != 0 || hor != 0) {
            //求实际距离
            float result = Mathf.Sqrt (hor * hor + ver * ver);
            //设置Speed参数
            ani.SetFloat ("Speed", Mathf.Abs (result));
        } else {
            //让角色停止移动
            ani.SetFloat ("Speed", -1f);
        }
    }

    void Turn(float hor,float ver)
    {
        //如果玩家按下了任意一个方向键
        if (hor != 0 || ver != 0) {
            //获取方向向量
            Vector3 dir = new Vector3 (hor, 0, ver);
            //获取方向向量所代表的四元数
            Quaternion qua = Quaternion.LookRotation (dir);
            //玩家缓慢移动到目标四元数所代表的旋转
            transform.rotation = Quaternion.Lerp (transform.rotation,
                qua, Time.deltaTime * turnSpeed);
        }
    }
}

 

Demo_玩家移动(主要注意动画的设置)