using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCamera : MonoBehaviour {
private Transform player;
private Vector3 offset;
public float cameraMoveSpeed = 3;
public float cameraRotateSpeed = 3;
private void Awake()
{
player = GameObject.FindWithTag("Player").transform;
offset = transform.position - player.position;
offset = new Vector3(0, offset.y, offset.z);
}
void Update () {
//摄像机预留位置5个,起点是当前位置,终点是玩家正上方endPos,从中取3个点分别是1/4 2/4 3/4的点
Vector3 beginPos = player.position + offset;
Vector3 endPos = player.position + offset.magnitude*Vector3.up;
Vector3 pos1 = Vector3.Lerp(beginPos, endPos, 0.25f);
Vector3 pos2 = Vector3.Lerp(beginPos, endPos, 0.50f);
Vector3 pos3 = Vector3.Lerp(beginPos, endPos, 0.75f);
Vector3[] posArray = new Vector3[] { beginPos, pos1, pos2, pos3, endPos };
//摄像机目标位置
Vector3 targetPos = posArray[0];
for(int i=0;i<5;i++)
{
//从当前i索引的位置向玩家方向发射一条射线,检测一下是否有障碍物,有的话就继续下一个
RaycastHit hit;
if(Physics.Raycast(posArray[i],player.position-posArray[i],out hit))//长度无限
{
if(hit.collider.tag!="Player")
{
continue;
}
else
{
targetPos = posArray[i];
break;
}
}
else
{
targetPos = posArray[i];
break;
}
}
transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * cameraMoveSpeed);
//角度上的差值运算方法:
//先保存当前摄像机角度
Quaternion nowRotation = transform.rotation;
//使用LookAt方法,将摄像机朝向玩家,然后transform.rotation就是最终摄像机要达到的角度
transform.LookAt(player.position);
//保存这个最终角度
Quaternion endRotation = transform.rotation;
transform.rotation = Quaternion.Lerp(nowRotation, endRotation, Time.deltaTime * cameraRotateSpeed);
}
}