您的位置:首页 > 移动开发 > Unity3D

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

2017-03-04 15:21 1041 查看
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;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity 脚本 c#