今天要实现的功能是利用WASD或是方向键实现人物平滑转身。
1.首先搭建一个简易的场景和人物,我在这里利用一个圆柱加一个cube代表人物,其次保证人物模型的本地坐标与世界坐标保持统一,如图所示
2.在人物身上添加PlayerController脚本,源码如下:
- using UnityEngine;
- using System.Collections;
-
- public class PlayerController : MonoBehaviour {
- float ver = 0;
- float hor = 0;
- public float turnspeed = 10;
-
-
- void Start () {
-
- }
-
-
- 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);
-
-
-
- }
- }
-
- }