Unity中实现人物平滑转身

       今天要实现的功能是利用WASD或是方向键实现人物平滑转身。

       1.首先搭建一个简易的场景和人物,我在这里利用一个圆柱加一个cube代表人物,其次保证人物模型的本地坐标与世界坐标保持统一,如图所示

Unity中实现人物平滑转身

2.在人物身上添加PlayerController脚本,源码如下:

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class PlayerController : MonoBehaviour {  
  5.     float ver = 0;  
  6.     float hor = 0;  
  7.     public float  turnspeed = 10;  
  8.   
  9.     // Use this for initialization  
  10.     void Start () {  
  11.           
  12.     }  
  13.       
  14.     // Update is called once per frame  
  15.     void Update () {  
  16.         hor = Input.GetAxis("Horizontal");  
  17.         ver = Input.GetAxis("Vertical");  
  18.   
  19.     }  
  20.     void Rotating (float hor, float ver)  
  21.     {  
  22.         //获取方向  
  23.         Vector3 dir = new Vector3 (hor,0,ver);  
  24.         //将方向转换为四元数  
  25.         Quaternion quaDir = Quaternion.LookRotation(dir,Vector3.up);  
  26.         //缓慢转动到目标点  
  27.         transform.rotation = Quaternion.Lerp(transform.rotation,quaDir,Time.fixedDeltaTime*turnspeed);  
  28.           
  29.   
  30.   
  31.     }  
  32.   
  33.     void FixedUpdate(){  
  34.   
  35.   
  36.         if(hor!= 0 ||ver!= 0 ){  
  37.             //转身  
  38.             Rotating(hor,ver);  
  39.           
  40.           
  41.   
  42.     }  
  43. }  
  44.   
  45. }