鼠标控制镜头围绕角色旋转
在unity中提供了轴向输入控制,这里选择Mouse X与Mouse Y来控制鼠标输入。
创建一个向量来存储当前镜头方向,并在update函数中更新鼠标控制后的方向。
private Vector3 angle;
angle.x += Input.GetAxis("Mouse X")*xSpeed*Time.deltaTime;
angle.y -= Input.GetAxis("Mouse Y")*ySpeed*Time.deltaTime;
通过Mathf.Clamp()函数来限制垂直方向旋转。
angle.y = Mathf.Clamp(angle.y, yMinLimit, yMaxLimit);
将移动后的方向转换为Quaternion,并赋值给相机。
Quaternion rotation = Quaternion.Euler(angle.y, angle.x, 0);
transform.rotation = rotation;
并更新相机位置,使角色在移动过程中相机跟随角色,其中camMultiple用来控制相机与角色之间距离,以角色中心点为中心,所以在后面保持y为1(角色高度为2)。
transform.position = rotation * oriPos*camMultiple + new Vector3(target.position.x,1,target.position.z);
总体代码为:
Vector3 oriPos;
public Transform target;
public float xSpeed=800f;
public float ySpeed=800f;
public float yMin=-20f;
public float yMax=60f;
public float camMultiple = 0.4f;
private Vector3 angle;
private void Awake()
{
oriPos = transform.position;
angle = transform.eulerAngles;
}
void Update()
{
angle.x += Input.GetAxis("Mouse X")*xSpeed*Time.deltaTime;
angle.y -= Input.GetAxis("Mouse Y")*ySpeed*Time.deltaTime;
angle.y = Mathf.Clamp(angle.y, yMin, yMax);
Quaternion rotation = Quaternion.Euler(angle.y, angle.x, 0);
transform.rotation = rotation;
transform.position = rotation * oriPos*camMultiple + new Vector3(target.position.x,1,target.position.z);
}