类似电视摄影的视角,相机固定在某处,跟随着画面中人物的移动而移动。 根据图上原理,我们可以利用三种属性更新相机位置 1)距离distance 2)水平旋转角度rot 3)竖直旋转角度roll
//距离
public float distance = 15;
private float maxDistance = 22f;
private float minDistance = 5f;
public float zoomSpeed = 0.2f;//缩放速度
//水平旋转
public float rot = 0;
public float rotSpeed = 5f;
//竖直旋转
public float roll = 30 * Mathf.PI * 2 / 360;
private float maxRoll = 70 * Mathf.PI * 2 / 360;
private float minRoll = -10f * Mathf.PI * 2 / 360;
public float rollSpeed = 2f;
处理水平旋转
public void Rotate()
{
float w = Input.GetAxis("Mouse X") * rotSpeed * Time.deltaTime;
rot -= w;
}
处理竖直旋转
public void Roll()
{
float w = Input.GetAxis("Mouse Y") * rollSpeed * Time.deltaTime;
roll -= w;
if (roll > maxRoll)
roll = maxRoll;
if (roll < minRoll)
roll = minRoll;
}
处理鼠标滚轮缩放距离
public void Zoom()
{
if(Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (distance > minDistance)
distance -= zoomSpeed;
}
else if(Input.GetAxis("Mouse ScrollWheel") <0)
{
if (distance < maxDistance)
distance += zoomSpeed;
}
}
在update函数中依照公式对相机位置进行处理,即可完成相机跟随
Rotate();
Roll();
Zoom();
Vector3 targetPos = target.transform.position;
Vector3 cameraPos;
float d = distance * Mathf.Cos(roll);
float hegiht = distance * Mathf.Sin(roll);
cameraPos.x = targetPos.x + d * Mathf.Cos(rot);
cameraPos.y = targetPos.y + hegiht;
cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
Camera.main.transform.position = cameraPos;
Camera.main.transform.LookAt(target.transform);
|