解決攝像機被遮擋問題

效果圖:

程式碼:

using UnityEngine;  
using System.Collections;  
public class CameraMOve : MonoBehaviour {
/// <summary>
/// 移動速度
/// </summary>
public float moveSpeed = 3f;
/// <summary>
/// 放置速度
/// </summary>
public float turnSpeed = 10f;
/// <summary>
/// 玩家
/// </summary>
private Transform player;
/// <summary>
/// 攝像機魚玩家之間的向量
/// </summary>
private Vector3 direction;
/// <summary>
/// 射線碰撞
/// </summary>
private RaycastHit hit;
/// <summary>
/// 攝像機與玩家之間的距離
/// </summary>
private float distance;
/// <summary>
/// 攝像機的觀測點
/// </summary>
private Vector3[] currentPoints;
void Start () {
player = GameObject.FindWithTag(Tags.Player).transform;
currentPoints = new Vector3[5];
distance = Vector3.Distance(transform.position, player.position );
//從攝像機指向玩家的偏移量
direction= player.position - transform.position;
}  
/// <summary>
/// 攝像機程式碼放到LateUpdate中
/// 物理操作程式碼放到FixedUpdate
/// </summary>
void LateUpdate () {
//Player與攝像機之間的距離
Vector3 startPoint = player.position - direction ;
//Player垂直上方 與攝像機同高的點
Vector3 endPoint = player.position   Vector3.up * distance;
//迴圈獲取 攝像機到Player上方 點之間的5個點
for (int i = 0; i < currentPoints.Length ; i  )
{
currentPoints[i] = Vector3.Lerp(startPoint, endPoint, i * 0.25f);
}
//取陣列中的一個值為預設位置
Vector3 viewPosition= currentPoints[0];
//迴圈呼叫射線檢測 找到能看到Player的點
for (int i=0;i<currentPoints.Length; i  )
{
if (CheckView (currentPoints[i]))
{
viewPosition = currentPoints[i];
break;
}
}
//重新整理位置
transform.position = Vector3.Lerp(transform.position, viewPosition, Time.deltaTime * moveSpeed);
//調整角度
SmoothRotate();
}
/// <summary>
/// 檢測能否看到玩家
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
bool CheckView(Vector3 pos) {
//獲取點到攝像機的位置
Vector3 dir = player.position - pos;
//發射射線
if(Physics .Raycast (pos ,dir ,out hit))
{
if(hit .collider .tag ==Tags .Player)
{
return true;
}
}
return false;
}
/// <summary>
/// 調整攝像機旋轉角度
/// </summary>
void SmoothRotate()
{
//獲取攝像機到Player的向量
Vector3 dir = player.position - transform.position;
//返回一個角度 這個角度就是朝向Player的夾角
Quaternion qua = Quaternion.LookRotation(dir );
//旋轉角度
transform.rotation = Quaternion.Lerp(transform.rotation, qua, Time.deltaTime * turnSpeed);
//鎖定yz軸 
transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, 0);
}    
}