今天要实现的功能是利用WASD或是方向键实现人物平滑转身。
1.首先搭建一个简易的场景和人物,我在这里利用一个圆柱加一个cube代表人物,其次保证人物模型的本地坐标与世界坐标保持统一,如图所示

2.在人物身上添加PlayerController脚本,源码如下:
-
using UnityEngine;
-
using System.Collections;
-
-
public class PlayerController : MonoBehaviour {
-
float ver = 0;
-
float hor = 0;
-
public float turnspeed = 10;
-
-
// Use this for initialization
-
void Start () {
-
-
}
-
-
// Update is called once per frame
-
void Update () {
-
hor = Input.GetAxis("Horizontal");
-
ver = Input.GetAxis("Vertical");
-
-
}
-
void Rotating (float hor, float ver)
-
{
-
//获取方向
-
Vector3 dir = new Vector3 (hor,0,ver);
-
//将方向转换为四元数
-
Quaternion quaDir = Quaternion.LookRotation(dir,Vector3.up);
-
//缓慢转动到目标点
-
transform.rotation = Quaternion.Lerp(transform.rotation,quaDir,Time.fixedDeltaTime*turnspeed);
-
-
-
-
}
-
-
void FixedUpdate(){
-
-
-
if(hor!= 0 ||ver!= 0 ){
-
//转身
-
Rotating(hor,ver);
-
-
-
-
}
-
}
-
-
}