Unity (七) 摄像机跟随:实现角色被障碍物挡住后,摄像机滑到正好能看到主角的位置





using
System.Collections; using System.Collections.Generic; using UnityEngine; public class CameroFollow : MonoBehaviour { //观察目标 public Transform followtarget; //观察向量 private Vector3 followDir; //观察偏移量 public float watchoffet = 1.5f; //可选观察点的个数 public int gears = 5; //射线碰撞检测器 private RaycastHit hit; //摄像机移动的速度 public float moveSpeed = 3f; //摄像机旋转的速度 public float turnSpeed = 10f; void Start () { followtarget = GameObject.FindGameObjectWithTag(Tags.Player).transform;//指定跟随的目标是标签为Player的 followDir = followtarget.position - transform.position; } void Update () { //观察点队列的起点 Vector3 startPos =followtarget.position- followDir ; //观察点队列的终点 Vector3 endPos = followtarget.position + followtarget.up*(startPos.y+watchoffet); //创建观察队列 Vector3[] points = new Vector3[gears]; //设置起始点 points[0] = startPos; //设置终点 points[points.Length - 1] = endPos; //设置中间点 for (int i = 1; i < points.Length-1; i++) { points[i] = Vector3.Lerp(startPos, endPos, (float) i / (points.Length - 1)); } //观察点结果(初始为起点坐标) Vector3 resultwatchPoint = startPos; for (int j = 0; j <points.Length; j++) { if (CanWatchTarget(points[j])) { resultwatchPoint = points[j]; break; } } //lerp到目标位置 transform.position = Vector3.Lerp(transform.position, resultwatchPoint, Time.deltaTime * moveSpeed); //获取方向 Vector3 dir = followtarget.position - transform.position; //转四元数 Quaternion targetQua = Quaternion.LookRotation(dir); //lerp到目标旋转 transform.rotation=Quaternion.Lerp(transform.rotation,targetQua,Time.deltaTime*turnSpeed); //旋转修正 transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, 0); } /// <summary> /// 能否看到目标 /// </summary> /// <param name="pos">传入的点</param> /// <returns>能看到或者不能看到</returns> bool CanWatchTarget( Vector3 pos) { //发射射线 if (Physics.Raycast(pos,followtarget.position-pos,out hit)) { //射线碰撞到玩家 if (hit.collider.CompareTag(Tags.Player)) { return true; } } return false; } }

 

posted @ 2017-09-08 17:14  鱼歌。  阅读(2236)  评论(0编辑  收藏  举报