首先,交代一下背景:人物只有一个idel和一个原地踏步walk的动画,要实现行走,摄像机跟随以及360度视角。
人物控制使用的CharacterController。
首先获取相机与人物的相对位置
offset = transform.position - target.transform.position;
startEulerAngles = target.transform.localEulerAngles;
offsetForRotate = offset;
根据按键获取移动方向,并转化为欧拉角赋值给人物
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)
+ new Vector3(0, transform.eulerAngles.y, 0)
- startEulerAngles;
旋转简单的写了水平360旋转,由于旋转会改变相对关系,所以需要实时回去当前的差值
if (Input.GetMouseButton(1))
{
transform.position = target.transform.position + offsetForRotate;
transform.RotateAround(target.transform.position, target.transform.up, Input.GetAxis("Mouse X"));
offsetForRotate = transform.position - target.transform.position;
}
整体代码:
using UnityEngine;
public class CameraController: MonoBehaviour {
public CharacterController target;//Player
[HideInInspector]
public bool isCanControl = true;
[SerializeField]
private float speed = 0.05f;
private Vector3 direction;//按键方向
private Vector3 startEulerAngles;//初始旋转
private Vector3 offset;//初始相对位置
private Vector3 offsetForRotate;//旋转后的相对位置
private void Awake ()
{
offset = transform.position - target.transform.position;
}
private void OnEnable()
{
startEulerAngles = target.transform.localEulerAngles;
offsetForRotate = offset;
}
private void FixedUpdate ()
{
if (!isCanControl)
return;
Move();
CameraFollow();
}
/// <summary>
/// 人物移动
/// </summary>
private void Move()
{
if (Mathf.Abs(Input.GetAxis("Vertical")) > 0 || Mathf.Abs(Input.GetAxis("Horizontal")) > 0)
{
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)
+ new Vector3(0, transform.eulerAngles.y, 0)
- startEulerAngles;
target.GetComponent<Animation>().Play("03_走");
target.Move(target.transform.forward * speed);
}
else
target.GetComponent<Animation>().Play("02_站立");
}
/// <summary>
/// 摄像机旋转跟随
/// </summary>
private void CameraFollow()
{
if (Input.GetMouseButton(1))
{
transform.position = target.transform.position + offsetForRotate;
transform.RotateAround(target.transform.position, target.transform.up, Input.GetAxis("Mouse X"));
offsetForRotate = transform.position - target.transform.position;
}
transform.position = target.transform.position + offsetForRotate;
}
}