实现简单地控制相机距离和角度
附加于相机上的代码:
private Transform player; //跟随目标
Vector3 tempPosition=Vector3.zero;
Vector3 offsetPosition; //相机距离目标之间的差向量
float distance = 0.0f;
public float speed = 1;
public float rotateSpeed = 4;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag(tags.player).transform;
transform.LookAt(player.position);
//计算差向量
offsetPosition = transform.position - player.position;
}
// Update is called once per frame
void Update () {
//控制相机跟随目标
transform.position = offsetPosition + player.position;
Rotate();
Distance();
}
//控制相机的拉近及拉远
void Distance()
{
distance = offsetPosition.magnitude;
//滚轮控制相机距离目标的距离
distance = distance + Input.GetAxis("Mouse ScrollWheel") * speed;
//控制最小与最大距离
distance = Mathf.Clamp(distance, 5, 20);
offsetPosition = offsetPosition.normalized * distance;
}
//控制相机围绕目标旋转
void Rotate()
{
if(Input.GetMouseButton(0))
{
Vector3 tempPos = transform.position;
Quaternion tempRot = transform.rotation;
transform.RotateAround(player.position, player.up, rotateSpeed * Input.GetAxis("Mouse X"));
//**注意这里围绕旋转的轴是相机本身的x轴,类似天体运动中的自转**
transform.RotateAround(player.position, transform.right, rotateSpeed * Input.GetAxis("Mouse Y"));
float x = transform.eulerAngles.x;
//限制旋转角度在10 - 80 之间
if(x<10||x>80)
{
transform.position = tempPos;
transform.rotation = tempRot;
}
}
//注意一定要在旋转后更新差向量
offsetPosition = transform.position - player.position;
}