首先,是确定方向:
new Vector3(Input.GetAxis("Vertical"), 0, -Input.GetAxis("Horizontal"))
然后,需要这个向量的单位向量:
direction = new Vector3(Input.GetAxis("Vertical"), 0, -Input.GetAxis("Horizontal")).normalized;
接下来,通过四元数将向量转化为欧拉角:
Quaternion.FromToRotation(Vector3.forward, direction).eulerAngles
但是,这样,人物有可能翻转,目测是万向锁问题,此处暂时还没有去仔细研究,算是用了个取巧的方法解决:
target.transform.eulerAngles = new Vector3(0, Quaternion.FromToRotation(Vector3.forward, direction).eulerAngles.y, 0);
完整代码:
/************************************************************
FileName: CameraController.cs
Author:末零 Version :1.0 Date: 2018-8-29
Description:人物行走
************************************************************/
using System.Collections;
using UnityEngine;
public class CameraController: MonoBehaviour {
public CharacterController target;
private Vector3 direction;
private Vector3 offset;
private void Start ()
{
offset = transform.position - target.transform.position;
}
private void FixedUpdate ()
{
Move();
CameraFollow();
}
private void Move()
{
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
direction = new Vector3(Input.GetAxis("Vertical"), 0, -Input.GetAxis("Horizontal")).normalized;
target.transform.eulerAngles = new Vector3(0, Quaternion.FromToRotation(Vector3.forward, direction).eulerAngles.y, 0);
target.GetComponent<Animation>().Play("03_走");
target.Move(direction * 0.05f);
}
else
target.GetComponent<Animation>().Play("02_站立");
}
private void CameraFollow()
{
transform.position = target.transform.position + offset;
}
}