解决摄像机被遮挡问题
程序员文章站
2022-07-05 21:51:47
...
效果图:
代码:
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);
}
}