1. 程式人生 > >unity 第三人稱控制物件平移轉向C#指令碼(親測有效)

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

}

    //一定注意當物件旋轉時,其區域性座標將改變,和世界座標不一樣了。。所以這裡用到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;
    }
}