unity 第三人称控制对象平移转向C#脚本(亲测有效)

using UnityEngine;
using System.Collections;


public class ControlMove : MonoBehaviour {

    public float move_speed;
    Animator animator;
    public float turn_speed;   //对象旋转的快慢控制
    Rigidbody M_rigidbody;     //对象身上绑定的刚体组件
    private float V=0;
    private float H=0;

    void Start () {
       animator = GetComponent();
        M_rigidbody = GetComponent();

}


    //一定注意当对象旋转时,其局部坐标将改变,和世界坐标不一样了。。所以这里用到vector3.forward,其永远指向对象的前方即 Z轴
    private void FixedUpdate()
    {
        V = Input.GetAxis("Vertical");
        H = Input.GetAxis("Horizontal");
        if (V!=0||H!=0)
        {
            Rotation(V, H);
            animator.SetBool("stand_walk", true);
            animator.SetBool("walk_stand", false);
            transform.Translate(Vector3.forward*move_speed*Time.deltaTime);
        }
        else
        {
            animator.SetBool("walk_stand", true);
            animator.SetBool("stand_walk", false);
        }
    }
    //这里运用到四元数来进行对象的旋转
    void Rotation(float vertical, float horizontal)
    {
        Vector3 targeDirection = new Vector3(horizontal,0f,vertical);
        Quaternion targetRotation = Quaternion.LookRotation(targeDirection, Vector3.up);
        Quaternion newRotation = Quaternion.Lerp(M_rigidbody.rotation, targetRotation, turn_speed * Time.deltaTime);
        transform.rotation=newRotation;
    }
}

你可能感兴趣的:(unity)